驗證碼和圖片上傳和多張圖片無刷新上傳

先來驗證碼通常處理程序編寫javascript

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Web;
 5 
 6 namespace Blog.UI
 7 {
 8     using System.Drawing;
 9     using Blog.Common;
10     /// <summary>
11     /// Vcode 的摘要說明
12     /// </summary>
13     public class Vcode : IHttpHandler,System.Web.SessionState.IRequiresSessionState
14     {
15         Random r = new Random();
16         public void ProcessRequest(HttpContext context)
17         {
18             //準備一張畫布
19             using (Image img = new Bitmap(60, 25))
20             {
21                 
22                 //準備一個畫家
23                 Graphics g = Graphics.FromImage(img);
24                 //背景畫白
25                 g.Clear(Color.White);
26                 //畫邊框
27                 g.DrawRectangle(Pens.Red, 0, 0, img.Width - 1, img.Height - 1);
28                 //畫噪點線
29                 DrawPoints(g, img, 10);
30                 //獲得驗證碼字符串
31                 string vcodestr = Getstring(1);
32                 //畫字符串
33                 g.DrawString(vcodestr, new Font("微軟雅黑", 16, FontStyle.Italic | FontStyle.Strikeout), Brushes.Blue, 0, 0);
34                 DrawPoints(g, img, 10);
35                 //將圖片以jpg格式顯示在outputstream流
36                 img.Save(context.Response.OutputStream, System.Drawing.Imaging.ImageFormat.Jpeg);
37                 //存進session
38                 context.Session[CommonHelper.Vcode] = vcodestr;
39             }
40         }
41         void DrawPoints(Graphics g,Image img,int n)
42         {
43             for (int i = 0; i < n; i++)
44             {
45                 int x = r.Next(0, img.Width);
46                 int y = r.Next(0, img.Height);
47                 g.DrawLine(Pens.Blue, x, y, x + r.Next(2, img.Width), y + r.Next(2, img.Width));
48             }
49             
50         }
51         string Getstring(int n)
52         {
53             string s = string.Empty;
54             
55             char[] c = new char[] { '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c','d' };
56             for (int i = 0; i < n; i++)
57             {
58                s+=c[ r.Next(c.Length)];
59             }
60             return s;
61         }
62         public bool IsReusable
63         {
64             get
65             {
66                 return false;
67             }
68         }
69     }
70 }
驗證碼

圖片上傳前臺用隱藏iframe來實現不刷新後臺相似驗證碼css

<%@ Page Language="C#" MasterPageFile="~/Master/Site1.Master" AutoEventWireup="true" CodeBehind="PhotoList.aspx.cs" Inherits="Blog.UI.Photo.PhotoList" %>

<%@ Register Assembly="AspNetPager" Namespace="Wuqi.Webdiyer" TagPrefix="bigying" %>
<asp:Content ID="heard" ContentPlaceHolderID="head" runat="server">
    <style type="text/css">
        .contentdiv
        {
            height: 200px;
            width: 130px;
            border: 1px solid blue;
            margin: 4px 2px;
            display: inline-block;
        }

            .contentdiv ul
            {
                text-align: center;
            }

        .pictureimg
        {
            width: 130px;
            height: 150px;
        }

        #pagingdiv
        {
            width: 400px;
            border: 1px solid red;
            position: relative;
            left: 320px;
            top: 250px;
        }
        #uploaddiv
        {
            width:200px;
            height:100px;
            border:1px solid red;
            margin:50px auto;
            display:none;
        }
    </style>
    <script src="/JS/jquery-1.9.1.min.js"></script>
    <script src="/JS/AjaxHelper.js"></script>
   <script type="text/javascript">

       //var pid;
       //var paid;
       function Delete(id)
       {
           alert(id);
       }
       function Showupload(pid,paid)
       {
           $("#uploaddiv").show();
           $("#pid").val(pid);
           $("#paid").val(paid);
       }
       function Cancleupload() {
           $("#uploaddiv").hide();
           
       }
       function Uploadphotoajax()
       {
           //手寫ajax複習
           //var xhr = new XMLHttpRequest();
           //xhr.open("post", "/Photo/upload.ashx", true);
           //xhr.setRequestHeader("content-type","multipart/form-data");
           //xhr.onreadystatechange = function () {
           //    if (xhr.status == 200 && xhr.readyState == 4)
           //    {
           //        alert(xhr.responseText);
           //    }
           //}
           //xhr.send($("#f1").serialize());
           //AjaxHelper.prcessPost("/Photo/upload.ashx", $("#f1").serialize(), function (ajaxobj) {
           //    alert(ajaxobj);
           //});
           $("#uploadLog").html("上傳中...");
           $("#f1").submit();
       }
       function uploadSuccess(msg)
       {
           if (msg.split('|').length > 1) {
               $("#imgShow").attr("src", msg.split('|')[1]);
               $("#uploadLog").html($("#uploadLog").html()+"<br/>"+msg.split('|')[0]);
           }
           else {
               alert(msg);
           }
       }
   </script>
</asp:Content>
<asp:Content ID="content" ContentPlaceHolderID="ContentPlaceHolder01" runat="server">
    <form runat="server">
    <asp:Repeater ID="Repeater1" runat="server" OnItemCommand="Repeater1_ItemCommand">
        <ItemTemplate>
            <div class="contentdiv">
            <ul>
                <li class="pictureli">
                    <img class="pictureimg" src="/Upload/Images/<%#Eval("Psrc")%>" /></li>
                <li><%#Eval("Ptitle") %></li>
                <li><asp:LinkButton ID="LinkButton1" runat="server" CommandArgument='<%#Eval("Pid") %>' CommandName="btnDel">刪除</asp:LinkButton>

                    <a href="javascript:void(0)" onclick="Edit(<%#Eval("Pid")%>)">修改</a>

                    <a href="javascript:void(0)" onclick='Showupload(<%#Eval("PId")%>,<%#Eval("PAlbum") %>)'>上傳</a>
                </li>
            </ul>
        </div>
           
        </ItemTemplate>
    </asp:Repeater>
   
    <div id="pagingdiv"> <bigying:AspNetPager ID="pager"  runat="server" AlwaysShow="true" FirstPageText="首頁" LastPageText="尾頁" NextPageText="後頁" PageIndexBoxType="TextBox" PrevPageText="前頁" ShowPageIndexBox="Always" SubmitButtonText="Go" TextAfterPageIndexBox="頁" TextBeforePageIndexBox="轉到" PageSize="5" OnPageChanged="pager_PageChanged"></bigying:AspNetPager>
        </div> </form>  
    <div id="uploaddiv">
        
        <%-- 這裏用一個隱藏的iframe,將form的target指向iframe,而該iframe是隱藏的,從而達到無刷新上傳,ajax通常操做字符串 --%>
        <form method="post" id="f1" enctype="multipart/form-data" action="upload.ashx" target="frame1">
          <%-- 隱藏控件保存paid和pid傳遞值 --%>
             <input type="hidden" id="paid" name="paid" />
            <input type="hidden" id="pid" name="pid" />
             <table >
                <tr>
                    <td><label id="uploadLog"></label></td>
                    <td><img width="40px" src="" id="imgShow" alt="縮略圖" /></td>
                </tr>
                <tr>
                    <td colspan="2">
                        <input type="file" name="filepath" multiple="multiple" id="fileajax" /></td>
                    
                </tr>
                <tr>
                    <td>
                        <input type="button" value="上傳" onclick="Uploadphotoajax()" /></td>
                    <td>
                        <input type="button" value="取消" onclick="Cancleupload()" /></td>
                </tr>

            </table>
        </form>
        <iframe style="display:none" name="frame1" id="frame1"></iframe>
       
    </div>
</asp:Content>
前臺
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace Blog.UI.Photo
{
    using Blog.BLL;
    using Blog.Model;
    using Blog.Common;
    using System.Drawing;
    /// <summary>
    /// upload 的摘要說明
    /// </summary>
    public class upload : IHttpHandler
    {

        public void ProcessRequest(HttpContext context)
        {
            if (context.Request.HttpMethod.ToLower() == "post")
            {
                Uploadphoto(context);
            }
        }

        private static void Uploadphoto(HttpContext context)
        {
            string paid = context.Request.Form["paid"];
            string pid = context.Request.Form["pid"];
            //獲得上傳來的文件集合判斷集合長度,遍歷集合元素由於多是多文件上傳
            HttpFileCollection myfilelist = context.Request.Files;
            if (myfilelist.Count > 0)
            {
                for (int i = 0; i < myfilelist.Count; i++)
                {
                    //判斷是否爲空文件,而且要求爲圖片文件
                    if (myfilelist[i].ContentLength > 3 && myfilelist[i].ContentType.StartsWith("image/"))
                    {
                        //舊名字到生成新名字隨機字符串
                        string oldname = myfilelist[i].FileName;
                        string suffixname = System.IO.Path.GetExtension(oldname);
                        string newname = Guid.NewGuid() + suffixname;
                        string path = "/Upload/Images/" + newname;
                        //把集合中圖片放進2進制流,把這個流建立一個img
                        using (Image img = Image.FromStream(myfilelist[i].InputStream))
                        {

                            img.Save(context.Server.MapPath(path));
                            //img.Save(context.Response.OutputStream, img.RawFormat);

                        }
                        BlogPhotoBLL bpBLL = new BlogPhotoBLL();

                        BlogPhoto model = bpBLL.GetModel(int.Parse(pid));
                        model.PSrc = newname;
                        if (bpBLL.Update(model))
                        {
                            context.Response.Write("<script>window.parent.uploadSuccess('" + oldname + "上傳成功|" + path + "');window.parent.location='/Photo/PhotoList.aspx?paid="+paid+"';</script>");
                            context.Response.End();
                        }
                        else
                        {
                            context.Response.Write("<script>window.parent.uploadSuccess('" + oldname + "上傳不成功|" + path + "');</script>");
                        }
                    }
                }

            }
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}
後臺

 

 1  /// <summary>
 2         /// 封裝上傳圖片方法支持多張上傳
 3         /// </summary>
 4         /// <param name="imgpath"></param>
 5         /// <param name="thumpath"></param>
 6         /// <param name="waterimgname"></param>
 7         private void Uploadphoto(string imgpath, string thumpath, string waterimgname)
 8         {
 9             HttpFileCollection hfclist = request.Files;
10             if (hfclist.Count > 0)
11             {
12                 // 遍歷獲得的文件集合
13                 for (int i = 0; i < hfclist.Count; i++)
14                 {
15                     //判斷集合中元素是否長度爲空,是不是圖片
16                     if (hfclist[i].ContentLength > 3 && hfclist[i].ContentType.StartsWith("image/"))
17                     {
18                         //上傳文件名稱
19                         string oldname = hfclist[i].FileName;
20                         //後綴名
21                         string extname = System.IO.Path.GetExtension(oldname);
22                         //生成新名字
23                         string newname = Guid.NewGuid().ToString() + extname;
24                         //
25                         
26                         //是就獲得後綴名,新建一個隨機文件名保存在/imgs文件夾下
27                         using (Image img = Image.FromStream(hfclist[i].InputStream))
28                         {
29                             //獲得縮略圖
30                             Image thumimg = img.GetThumbnailImage(130, 150, null, System.IntPtr.Zero);
31 
32                             thumimg.Save(thumpath+newname);
33                            
34                             using (Image imgwater = Image.FromFile(thumpath + waterimgname))
35                             {
36                                 //獲得水印圖片/imgs/mywater.png打水印
37                                 using (Graphics g = Graphics.FromImage(img))
38                                 {
39                                     //在指定矩形位置畫指定矩形大小圖像
40                                     g.DrawImage(imgwater, new Rectangle(0, 0, 40, 40), new Rectangle(4, 4, imgwater.Width , imgwater.Height), GraphicsUnit.Pixel);
41                                     //存起來
42                                     img.Save(imgpath + newname + "");
43                                     response.Write("<script>window.parent.Uploadresponse('" + oldname + "+上傳成功|+" + newname + "')</script>");
44                                 }
45                             }
46 
47                         }
48 
49                     }
50                 }
本身封裝的上傳多張圖片的方法,能夠複用

 

作分頁的時候使用了兩套分頁插件,一套前臺分頁插件jpaginate demo  一套後臺自定義控件 aspnetpager.dll       html

 

2.0ajax技術結合json格式處理增刪改查java

3.0session 和cookie結合實現免登錄jquery

4.0進程外session   ajax

1.0使用狀態服務器存session
開啓狀態服務器。配置配置文件//默認端口42424
<sessionstate stateconnectionstring ="tcpip=127.0.0.1:42424" mode="StateServer"/>sql

2.0使用數據庫存session
去到fw文件夾中執行建立session數據庫的腳本
c:windows\microsoft.net\framwork\v4.0...
數據庫 帳號 密碼
執行cmd命令aspnet_regsql –S . -U sa -P master –ssadd -sstype c -d aspnetdb數據庫

 

5.0緩存    頁面緩存 數據緩存json

01 整頁緩存<% @outputcache duration="10" varybyparam="none"%>
02 參數緩存<% @outputcache duration="10" varybyparam="id;name"%>
03根據頁面控件緩存 <% @outputcache duration="10" varybyparam="none" varybycontrol="Dropdownlist1"%>
04控件緩存(片斷緩存,局部緩存)
.ascx中設置整頁緩存windows

數據緩存

絕對時間緩存
相對時間緩存
文件依賴緩存 文件依賴項改變時候緩存重置
數據庫依賴緩存 數據庫表依賴項改變時候緩存重置

 

簡單工廠模式

  解決緊耦合問題,思想是加多一個接口層,一個factory工廠層。斷開bll層對dal層的聯繫。使用工廠返回接口對象(實現了接口的對象)用接口接收。

相關文章
相關標籤/搜索