C#中使用iframe結合js實現圖片非同步上傳,
將圖片上傳的頁面放在iframe中,通過iframe跳轉到另一個頁面,在該頁中將圖片提交到伺服器,而不需要對首頁進行重新整理,提交成功後用指令碼(回呼函數)實現上傳的圖片在首頁面的顯示。
圖片選擇頁面 Add.aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Add.aspx.cs" Inherits="_Add" %><!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 id="Head1" 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");document.getElementById("picUrl").value = str;str = "../images/" + str;theImg.setAttribute("src", str);} </script></head><body> <form id="form1" runat="server"> <div> <iframe src="Print/PicUpload.aspx" id="uploadframe" style="display: none;"></iframe> <p> <asp:Image ID="imgResult" runat="server" Width="80" Height="112" /> </p> <p> <input type="button" id="btnBrowser" value="選擇檔案" onclick="doUpload()" /> </p> <h5> 上傳圖片格式為.jpg, .gif, .bmp,.png,圖片大小不得超過8M</h5> </div> <input id="picUrl" type="hidden" runat="server" value="" /> </form></body></html>
圖片上傳處理頁面
前台 PicUpload.aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="PicUpload.aspx.cs" Inherits="Web.Print.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("<%=pic_upload.ClientID%>"); theFileUpload.onchange = function () { var fileExt = theFileUpload.value.substr(theFileUpload.value.lastIndexOf(".")); //判斷檔案打大小 if(theFileUpload.files[0].size>8192000) { top.alert("檔案大小超出8M!請重新選擇!"); } else { //驗證是不是圖片 if (!fileExt.match(/\.jpg|\.png|\.bmp|\.gif/i)) { top.alert("只能上傳jpg,gif,bmp,png圖片!"); } else { var myForm = document.getElementById("<%=form1.ClientID%>"); myForm.submit(); } } } theFileUpload.click(); } //回呼函數 function callback(filePath) { parent.callback(filePath); //也可用top.callback,But,若Add.aspx是其他頁面通過iframe 跳轉到的(如在index.aspx 通過<iframe src="Add.aspx"></iframe> 跳轉到Add.aspx), //則top.callback無法回調到Add.aspx,而parent.callback可以回調到Add.aspx } </script> </head><body> <form id="form1" runat="server"> <asp:ScriptManager ID="ScriptManager1" runat="server" > </asp:ScriptManager> <div> <asp:FileUpload runat="server" ID="pic_upload"></asp:FileUpload> </div> </form></body></html>後台圖片上傳事件及促發回呼函數處理
PicUpload.aspx.cs:
using System;using System.Collections;using System.Configuration;using System.Data;using System.Linq;using System.Web;using System.Web.Security;using System.Web.UI;using System.Web.UI.HtmlControls;using System.Web.UI.WebControls;using System.Web.UI.WebControls.WebParts;using System.Xml.Linq;using System.IO;using System.Security.Cryptography;namespace Web.Print{ public partial class PicUpload : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { if (IsPostBack && pic_upload.HasFile) { //取得檔案的副檔名,並轉換成小寫 string fileExtension = Path.GetExtension(pic_upload.FileName).ToLower(); string filepath = "/images/"; if (Directory.Exists(Server.MapPath(filepath)) == false)//如果不存在就建立file檔案夾 { Directory.CreateDirectory(Server.MapPath(filepath)); } string hash = CreatePasswordHash(pic_upload.FileName, 4); string virpath = filepath + hash + fileExtension;//這是存到伺服器上的虛擬路徑 string mappath = Server.MapPath(virpath);//轉換成伺服器上的實體路徑 pic_upload.SaveAs(mappath); ScriptManager.RegisterStartupScript(this, this.GetType(), "callback", "callback('" + hash + fileExtension + "');", true); } } /// <summary> /// 建立一個指定長度的隨機salt值 /// </summary> public string CreateSalt(int saltLenght) { //產生一個加密的隨機數 RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider(); byte[] buff = new byte[saltLenght]; rng.GetBytes(buff); //返回一個Base64隨機數的字串 return Convert.ToBase64String(buff); } /// <summary> /// 返回加密後的字串 /// </summary> public string CreatePasswordHash(string pwd, int saltLenght) { string strSalt = CreateSalt(saltLenght); //把密碼和Salt連起來 string saltAndPwd = String.Concat(pwd, strSalt); //對密碼進行雜湊 string hashenPwd = FormsAuthentication.HashPasswordForStoringInConfigFile(saltAndPwd, "sha1"); //轉為小寫字元並截取前16個字串 hashenPwd = hashenPwd.ToLower().Substring(0, 16); //返回雜湊後的值 return hashenPwd; } }}