原理:將圖片上傳的頁面放在iframe中,這樣就可以在iframe中將圖片提交到服務器而不需要頁面刷新,提交成功后用腳本實現主頁面顯示上傳的圖片。
Default.aspx:
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title></title> <script type="text/javascript"> function doUpload() { var theFrame = document.getElementById("uploadframe"); if (theFrame) { theFrame = theFrame.contentWindow; theFrame.selectAndUpload(); } } function callback(str) { var theImg = document.getElementById("imgResult"); theImg.setAttribute("src", str); } </script> </head> <body> <form id="form1" runat="server"> <div> <h1> Asp.net 異步上傳示例</h1> <iframe src="PicUpload.aspx" id="uploadframe" style="display: none;"></iframe> <p> <input type="button" id="btnBrowser" value="選擇文件" onclick="doUpload()" /> </p> <h2> 上傳結果</h2> <p> <img alt="上傳后的圖片" id="imgResult" style="width: 400px" /> </p> </div> </form> </body> </html>
PicUpload.aspx:
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="PicUpload.aspx.cs" Inherits="PicUpload" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title></title> <script type="text/javascript"> function selectAndUpload() { var theFileUpload = document.getElementById("<%=fileUpload1.ClientID%>"); theFileUpload.onchange = function () { var fileExt = theFileUpload.value.substr(theFileUpload.value.lastIndexOf(".")); if (!fileExt.match(/\.jpg|\.png|\.gif/i))//驗證一下是不是圖片 { top.alert("只能上傳jpg,png,gif圖片。"); } else { var myForm = document.getElementById("<%=form1.ClientID%>"); myForm.submit(); } } theFileUpload.click(); } function callback(filePath) { top.callback(filePath); } </script> </head> <body> <form id="form1" runat="server"> <div> <asp:FileUpload runat="server" ID="fileUpload1"></asp:FileUpload> </div> </form> </body> </html>
PicUpload.aspx.cs:
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; public partial class PicUpload : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { if (IsPostBack && fileUpload1.HasFile) { string path = Server.MapPath("~/upload/" + fileUpload1.FileName); fileUpload1.SaveAs(path); ClientScript.RegisterClientScriptBlock(this.GetType(), "callback", "callback('upload/" + fileUpload1.FileName + "')", true); } } }