让ASP.NET的FileUpload控件支持浏览自动上传功能

FileUpload控件默认不支持服务端的ONCHANGE事件,此时用一种变通的方法借用客户端的onchange事件,调用__doPostBack方法来用LinkButton的OnClick事件模拟一个事件触发的过程,具体代码如下:


客户端:

  1. <asp:FileUpload ID="fuPhoto" onchange="javascript:__doPostBack('lbUploadPhoto','')" 
  2.                                 runat="server" ToolTip="选择图片" /> 
  3. <asp:LinkButton ID="lbUploadPhoto" runat="server" OnClick="lbUploadPhoto_Click"></asp:LinkButton> 

后台代码:

  1. //自动上传事件 
  2.        protected void lbUploadPhoto_Click(object sender, EventArgs e) 
  3.        { 
  4.            fileUpload(); 
  5.        } 
  6.        //从控件上传文件 
  7.        public void fileUpload() 
  8.        { 
  9.            if (fuPhoto.PostedFile != null && fuPhoto.PostedFile.ContentLength > 0) 
  10.            { 
  11.                string ext = System.IO.Path.GetExtension(fuPhoto.PostedFile.FileName).ToLower(); 
  12.                if (ext != ".jpg" && ext != ".jepg" && ext != ".bmp" && ext != ".gif"
  13.                { 
  14.                    return
  15.                } 
  16.                string filename = "Image_" + DateTime.Now.ToString("yyyyMMddHHmmss") + ext; 
  17.                string path = "./UploadPhoto/" + filename; 
  18.                fuPhoto.PostedFile.SaveAs(Server.MapPath(path)); 
  19.                Response.Redirect("ImageCut.aspx?Picurl=" + Server.UrlEncode(path)); 
  20.            } 
  21.            else 
  22.            { 
  23.                //do some thing; 
  24.            } 
  25.        } 

你可能感兴趣的:(fileupload)