最近要作微信的圖文上傳,由於一個圖文了表中能夠有多個圖文,全部按鈕須要隨時添加,因此作了一種無刷新上傳的方法。javascript
首先咱們要在html頁面中寫上這樣的幾段代碼html
javascript:前端
$(function () { //這個是爲了綁定咱們全部的上傳按鈕,包括動態添加的按鈕 $(document).on("change", ".filebutton", function () { $(this).parent().children("span").html('開始上傳中....'); $(this).parent().submit(); }); }) //這個方法是爲了讓iframe中的頁面調用修改本頁內容的方法(能夠根據本身須要修改) function uploadSuccess(msg) { var info = msg.split('|'); var _from = $("#" + info[2] + "_ts"); _from.html(info[0]); if (info[1] != "") { _from.append("<a href='uplod/" + info[1] + "' target=\"_blank\" imgurl=\"" + info[1] + "\">查看圖片</a>"); } else { _from.append("<a imgurl=\"\"></a>"); } }
htmljava
<form method="post" action="../ajax/Upload.ashx?id=boximg" target='boximg_f' enctype="multipart/form-data"><!--這裏用到了target屬性來指向下面的iframe讓頁面在iframe中刷新--> <input class="filebutton" type="file" id="boximg" name="fileUp" /> <span id="boximg_ts" runat="server" class="help-inline">上傳的文件不能大於500KB</span>
</form> <!--這裏隱藏這個iframe讓別人看不出來刷新的效果--> <iframe id="boximg_f" name="boximg_f" style="display:none;"></iframe>
而後咱們須要創建這個Upload.ashx文件來接收post過來的文件數據ajax
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.IO; using System.Net; using System.Text; using System.Web.UI; using System.Web.UI.WebControls; using System.Data; using System.Data.SqlClient; using WeiXinHaiBLL; namespace WeiXinHai.ajax { /// <summary> /// Upload 的摘要說明 /// </summary> public class Upload : IHttpHandler { public void ProcessRequest(HttpContext context) { context.Response.ContentType = "text/plain"; //string fname = context.Request.QueryString["op"].ToString(); //string str =fname+"({name:'judy',age:'23'})"; string id = context.Request.QueryString["id"]; try { //獲取當前Post過來的file集合對象,在這裏我只獲取了<input type='file' name='fileUp'/>的文件控件 string file1 = ""; if (id == "citu") { file1 = "fileUps"; } else { file1 = "fileUp"; } HttpPostedFile file = context.Request.Files[file1]; if (file != null) { //當前文件後綴名 string ext = Path.GetExtension(file.FileName).ToLower(); //驗證文件類型是否正確 if (!ext.Equals(".gif") && !ext.Equals(".jpg") && !ext.Equals(".png") && !ext.Equals(".bmp")) { //ajax/uplodereturn.html //這裏window.parent.uploadSuccess()是我在前端頁面中寫好的javascript function,此方法主要用於輸出異常和上傳成功後的圖片地址 context.Response.Redirect("uplodereturn.html?error=fileerror&id=" + id, false); return; } //驗證文件的大小 if (file.ContentLength > (1024 * 500)) { //這裏window.parent.uploadSuccess()是我在前端頁面中寫好的javascript function,此方法主要用於輸出異常和上傳成功後的圖片地址 context.Response.Redirect("uplodereturn.html?error=tobig&id=" + id, false); return; } FileInfo files = new FileInfo(file.FileName); //當前文件上傳的目錄 string serverPath = System.Web.HttpContext.Current.Server.MapPath("~"); string selfPath = "images\\uplod\\"; //當前待上傳的服務端路徑 string toFilePath = Path.Combine(serverPath, selfPath); //生成將要保存的隨機文件名 string fileName = GetImageName() + ext; //得到要保存的文件路徑 string serverFileName = toFilePath + fileName; //物理完整路徑 string toFileFullPath = serverFileName; //HttpContext.Current.Server.MapPath(toFilePath); //將要保存的完整文件名 string toFile = toFileFullPath;//+ fileName; context.Request.Files[0].SaveAs(toFile); //開始上傳 //file.SaveAs(imageUrl); //這裏window.parent.uploadSuccess()是我在前端頁面中寫好的javascript function,此方法主要用於輸出異常和上傳成功後的圖片地址 //若是成功返回的數據是須要返回兩個字符串,我在這裏使用了|分隔 例: 成功信息|/Test/hello.jpg context.Response.Redirect("uplodereturn.html?type=" + fileName + "&id=" + id, false); return; } else { //上傳失敗 context.Response.Redirect("uplodereturn.html?r=a&id=" + id, false); return; } } catch (Exception ex) { //上傳失敗 context.Response.Redirect("uplodereturn.html?r=a&id=" + id, false); return; } //context.Response.Write("hello word") } public bool IsReusable { get { return false; } } #region Private Methods /// <summary> /// 檢查是否爲合法的上傳圖片 /// </summary> /// <param name="_fileExt"></param> /// <returns></returns> private bool CheckImageExt(string _ImageExt) { string[] allowExt = new string[] { ".jpg", ".png", ".bmp", ".gif", ".pdf", ".jpeg", }; for (int i = 0; i < allowExt.Length; i++) { if (allowExt[i] == _ImageExt) { return true; } } return false; } private string GetImageName() { Random rd = new Random(); StringBuilder serial = new StringBuilder(); serial.Append(DateTime.Now.ToString("yyyyMMddHHmmssff")); serial.Append(rd.Next(0, 999999).ToString()); return serial.ToString(); } #endregion } }
剩下的咱們就要新建一個用來調用ifarme父級uploadSuccess方法的頁面uplodereturn.html微信
這個頁面要和上面的通常處理程序在一個文件夾內app
<!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> <title></title> <script> var url = window.location.search; if (url.indexOf("?") != -1) { var strurl = url.substr(1) strs = strurl.split("&"); var returntype = ''; if ([strs[0].split("=")[0]] == 'type') { returntype = "上傳成功|" + unescape(strs[0].split("=")[1]); //window.parent.uploadSuccess("上傳成功|" + unescape(strs[0].split("=")[1])); } else if ([strs[0].split("=")[0]] == 'error') { returntype = (unescape(strs[0].split("=")[1]) == "fileerror" ? "文件格式錯誤" : "上傳文件過大,請從新上傳!") + "|"; //window.parent.uploadSuccess(unescape(strs[0].split("=")[1])); } if (strs[1].split("=")[0] == 'id') { returntype += "|" + unescape(strs[1].split("=")[1]); } window.parent.uploadSuccess(returntype); } </script> </head> <body> </body> </html>
而後大功告成,咱們添加的時候須要添加上最上面的html代碼中的form部分就能夠了dom
這裏的原理是用from 的target 來讓這個from的刷新過程在iframe中進行,這樣的話咱們隱藏掉iframe的時候就看不出頁面的刷新效果
post
同時咱們又在這個新建的html中拼寫好咱們想要的參數調用父級寫好的方法,而後達到更改頁面的效果。ui
這裏個人方法是修改了span部分的內容。