ASP.NET的FileUpload控件默認是不支持服務端的onchange事件的,此時可以用一種變通的方法來實現這一功能。
這就需要借用客戶端的onchange事件,調用__doPostBack方法來用LinkButton的OnClick事件模擬一個事件觸發的過程,具體代碼如下:
客戶端:
<asp:FileUpload ID="fuPhoto" onchange="javascript:__doPostBack('lbUploadPhoto','')" runat="server" ToolTip="選擇圖片" /> <asp:LinkButton ID="lbUploadPhoto" runat="server" OnClick="lbUploadPhoto_Click"></asp:LinkButton>
後台代碼:
//自動上傳事件 protected void lbUploadPhoto_Click(object sender, EventArgs e) { fileUpload(); } //從控件上傳文件 public void fileUpload() { if (fuPhoto.PostedFile != null && fuPhoto.PostedFile.ContentLength > 0) { string ext = System.IO.Path.GetExtension(fuPhoto.PostedFile.FileName).ToLower(); if (ext != ".jpg" && ext != ".jepg" && ext != ".bmp" && ext != ".gif") { return; } string filename = "Image_" + DateTime.Now.ToString("yyyyMMddHHmmss") + ext; string path = "./UploadPhoto/" + filename; fuPhoto.PostedFile.SaveAs(Server.MapPath(path)); Response.Redirect("ImageCut.aspx?Picurl=" + Server.UrlEncode(path)); } else { //do some thing; } }