一、需要的材料
客戶端需要一個HTML頁面A其中包含一個iframe和一個form表單,一個頁面B(我稱之為客戶端代理)里面包含對返回參數的處理;
服務端需要一個asp.net的一般處理程序用來處理上傳文件並返回值。
二、原理圖
有圖才有真相,哈哈哈
三、客戶端代碼實現
1、頁面A的實現
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>A頁面</title> <script src="http://libs.baidu.com/jquery/2.0.0/jquery.min.js"></script> </head> <body> <iframe name='hidden_frame' id="hidden_frame" style='display:none'></iframe> <form id="fileform" method="post" enctype="multipart/form-data" target="hidden_frame"> <input type="file" name="fileUpload" /> </form> <button id="submitbtn">開始上傳</button> <script type="text/javascript"> function callback(msg) { //回調函數 alert(msg); } </script> <script type="text/javascript"> $("#submitbtn").click(function() { var callbackurl = window.location.href.substring(0, window.location.href.lastIndexOf('/')) + "proxy.html"; //獲取代理文件路徑 $("#fileform").attr("action", "FileHandler.ashx?callbackurl=" + callbackurl); $("#fileform").submit(); }) </script> </body> </html>
2.代理頁面實現 proxy.html 為了方便調用,我將該頁面放在了與A頁面同一目錄下,也可以不同目錄,但必須是同域
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>代理文件</title> </head> <body> <script type="text/javascript"> var rs = window.location.search.split('?').slice(1); window.parent.callback(rs.toString().split('=').slice(1));//調用父頁面的方法 </script> </body> </html>
三、服務端實現
public void ProcessRequest(HttpContext context) { context.Response.ContentType = "text/html"; HttpServerUtility server = context.Server; HttpRequest request = context.Request; HttpResponse response = context.Response; string callbackurl = context.Request["callbackurl"]; HttpPostedFile file = context.Request.Files[0]; if (file.ContentLength > 0) { string extName = Path.GetExtension(file.FileName); string fileName = Guid.NewGuid().ToString(); string fullName = fileName + extName; string imageFilter = ".jpg|.png|.gif|.ico";// 隨便模擬幾個圖片類型 if (imageFilter.Contains(extName.ToLower())) { string phyFilePath = server.MapPath("~/Upload/Image/") + fullName; file.SaveAs(phyFilePath); context.Response.Redirect(callbackurl + "?msg='上傳成功'") } } }
四、該方法的優缺點以及適用范圍
優點:沒有兼容性問題,在常見的瀏覽器中都是適用的;
缺點:返回數據最大支持2KB,對於較大的數據范圍建議使用CORS方式跨域
適用范圍:上傳文件,返回值只是一些短信息比如返回上傳正確與否。