需要注意的地方 这里文件域 必须有 id 和name
<input type="file" name="file1" id="file1" style=" 300px" />
需要引入的js ajaxfileupload.js 做过修改
1 var uploadHelper = { 2 handleError: function (s, xhr, status, e) { 3 // If a local callback was specified, fire it 4 if (s.error) { 5 s.error.call(s.context || s, xhr, status, e); 6 } 7 8 // Fire the global callback 9 if (s.global) { 10 (s.context ? jQuery(s.context) : jQuery.event).trigger("ajaxError", [xhr, s, e]); 11 } 12 }, 13 createUploadIframe: function (id, uri) { 14 //create frame 15 var frameId = 'jUploadFrame' + id; 16 var iframeHtml = '<iframe id="' + frameId + '" name="' + frameId + '" style="position:absolute; top:-9999px; left:-9999px"'; 17 if (window.ActiveXObject) { 18 if (typeof uri == 'boolean') { 19 iframeHtml += ' src="' + 'javascript:false' + '"'; 20 21 } 22 else if (typeof uri == 'string') { 23 iframeHtml += ' src="' + uri + '"'; 24 25 } 26 } 27 iframeHtml += ' />'; 28 jQuery(iframeHtml).appendTo(document.body); 29 30 return jQuery('#' + frameId).get(0); 31 }, 32 createUploadForm: function (id, fileElementId, data) { 33 debugger; 34 //create form 35 var formId = 'jUploadForm' + id; 36 var fileId = 'jUploadFile' + id; 37 var form = jQuery('<form action="" method="POST" name="' + formId + '" id="' + formId + '" enctype="multipart/form-data"></form>'); 38 if (data) { 39 for (var i in data) { 40 jQuery('<input type="hidden" name="' + i + '" value="' + data[i] + '" />').appendTo(form); 41 } 42 } 43 var oldElement = jQuery('#' + fileElementId); 44 var newElement = jQuery(oldElement).clone(); 45 jQuery(oldElement).attr('id', fileId); 46 jQuery(oldElement).before(newElement); 47 jQuery(oldElement).appendTo(form); 48 49 50 51 //set attributes 52 jQuery(form).css('position', 'absolute'); 53 jQuery(form).css('top', '-1200px'); 54 jQuery(form).css('left', '-1200px'); 55 jQuery(form).appendTo('body'); 56 return form; 57 }, 58 59 ajaxFileUpload: function (s) { 60 // TODO introduce global settings, allowing the client to modify them for all requests, not only timeout 61 s = jQuery.extend({}, jQuery.ajaxSettings, s); 62 var id = new Date().getTime() 63 var form = uploadHelper.createUploadForm(id, s.fileElementId, (typeof (s.data) == 'undefined' ? false : s.data)); 64 var io = uploadHelper.createUploadIframe(id, s.secureuri); 65 var frameId = 'jUploadFrame' + id; 66 var formId = 'jUploadForm' + id; 67 // Watch for a new set of requests 68 if (s.global && !jQuery.active++) { 69 jQuery.event.trigger("ajaxStart"); 70 } 71 var requestDone = false; 72 // Create the request object 73 var xml = {} 74 if (s.global) 75 jQuery.event.trigger("ajaxSend", [xml, s]); 76 // Wait for a response to come back 77 var uploadCallback = function (isTimeout) { 78 var io = document.getElementById(frameId); 79 try { 80 if (io.contentWindow) { 81 xml.responseText = io.contentWindow.document.body ? io.contentWindow.document.body.innerHTML : null; 82 xml.responseXML = io.contentWindow.document.XMLDocument ? io.contentWindow.document.XMLDocument : io.contentWindow.document; 83 84 } else if (io.contentDocument) { 85 xml.responseText = io.contentDocument.document.body ? io.contentDocument.document.body.innerHTML : null; 86 xml.responseXML = io.contentDocument.document.XMLDocument ? io.contentDocument.document.XMLDocument : io.contentDocument.document; 87 } 88 } catch (e) { 89 uploadHelper.handleError(s, xml, null, e); 90 } 91 if (xml || isTimeout == "timeout") { 92 requestDone = true; 93 var status; 94 try { 95 status = isTimeout != "timeout" ? "success" : "error"; 96 // Make sure that the request was successful or notmodified 97 if (status != "error") { 98 // process the data (runs the xml through httpData regardless of callback) 99 var data = uploadHelper.uploadHttpData(xml, s.dataType); 100 // If a local callback was specified, fire it and pass it the data 101 if (s.success) 102 s.success(data, status); 103 104 // Fire the global callback 105 if (s.global) 106 jQuery.event.trigger("ajaxSuccess", [xml, s]); 107 } else 108 jQuery.handleError(s, xml, status); 109 } catch (e) { 110 status = "error"; 111 uploadHelper.handleError(s, xml, status, e); 112 } 113 114 // The request was completed 115 if (s.global) 116 jQuery.event.trigger("ajaxComplete", [xml, s]); 117 118 // Handle the global AJAX counter 119 if (s.global && ! --jQuery.active) 120 jQuery.event.trigger("ajaxStop"); 121 122 // Process result 123 if (s.complete) 124 s.complete(xml, status); 125 126 jQuery(io).unbind() 127 128 setTimeout(function () { 129 try { 130 jQuery(io).remove(); 131 jQuery(form).remove(); 132 133 } catch (e) { 134 jQuery.handleError(s, xml, null, e); 135 } 136 137 }, 100) 138 139 xml = null 140 141 } 142 } 143 // Timeout checker 144 if (s.timeout > 0) { 145 setTimeout(function () { 146 // Check to see if the request is still happening 147 if (!requestDone) uploadCallback("timeout"); 148 }, s.timeout); 149 } 150 try { 151 152 var form = jQuery('#' + formId); 153 jQuery(form).attr('action', s.url); 154 jQuery(form).attr('method', 'POST'); 155 jQuery(form).attr('target', frameId); 156 if (form.encoding) { 157 jQuery(form).attr('encoding', 'multipart/form-data'); 158 } 159 else { 160 jQuery(form).attr('enctype', 'multipart/form-data'); 161 } 162 jQuery(form).submit(); 163 164 } catch (e) { 165 jQuery.handleError(s, xml, null, e); 166 } 167 168 jQuery('#' + frameId).load(uploadCallback); 169 return { abort: function () { } }; 170 171 }, 172 173 uploadHttpData: function (r, type) { 174 var data = !type; 175 data = type == "xml" || data ? r.responseXML : r.responseText; 176 // If the type is "script", eval it in global context 177 if (type == "script") 178 jQuery.globalEval(data); 179 // Get the JavaScript object, if JSON is used. 180 if (type == "json") 181 eval("data = " " + data + " " "); 182 // evaluate scripts within html 183 if (type == "html") 184 jQuery("<div>").html(data).evalScripts(); 185 186 return data; 187 } 188 189 };
调用 上传
1 var sId = "file1"; 2 if ((document.all[sId].value.indexOf(".xls") == -1) && (document.all[sId].value.indexOf(".xlsx") == -1)) { 3 alert("请选择Excel文件"); 4 return; 5 } 6 debugger; 7 uploadHelper.ajaxFileUpload({ 8 url: 'ashx/Uploads.ashx', //用于文件上传的服务器端请求地址 9 secureuri: false, //是否需要安全协议,一般设置为false 10 fileElementId: '' + sId, //文件上传域的ID 11 dataType: 'json', //返回值类型 一般设置为json 12 type: 'post', 13 success: function (data, status) //服务器成功响应处理函数 14 { 15 16 alert("上传成功" + data) 17 return; 18 19 }, 20 error: function (data, status, e)//服务器响应失败处理函数 21 { 22 alert(e); 23 } 24 });
后台 接收 C# Uploads.ashx
1 <%@ WebHandler Language="C#" Class="Uploads" %> 2 3 using System; 4 using System.Web; 5 using System.IO; 6 7 public class Uploads : IHttpHandler { 8 9 10 public void ProcessRequest(HttpContext context) 11 { 12 context.Response.ContentType = "text/html"; 13 upLoad(context); 14 //context.Response.Write("Hello World"); 15 } 16 17 public bool IsReusable 18 { 19 get 20 { 21 return false; 22 } 23 } 24 public void upLoad(HttpContext context) 25 { 26 string strErr = ""; 27 try 28 { 29 strErr = "{ 'error':'xxxxxx', 'msg':'错误','imgurl':'错误','newFilename':'错误'}"; 30 HttpFileCollection files = HttpContext.Current.Request.Files; 31 string msg = string.Empty; 32 string error = string.Empty; 33 string imgurl; 34 string newFilename; 35 if (files.Count > 0) 36 { 37 string path = context.Server.MapPath("~/App/files/"); 38 if (!Directory.Exists(path)) 39 { 40 // Create the directory it does not exist. 41 Directory.CreateDirectory(path); 42 } 43 44 45 Random rd = new Random(); 46 newFilename = DateTime.Now.ToString("yyyyMMddHHmmssffff") + rd.Next(0, 9999).ToString("0000") + System.IO.Path.GetFileName(files[0].FileName); 47 files[0].SaveAs(path + newFilename); 48 msg = " 成功! 文件路径为:" + path + newFilename; 49 imgurl = System.IO.Path.GetFileName(files[0].FileName); 50 strErr = "{ 'error':'" + error + "', 'msg':'" + msg + "','imgurl':'" + imgurl + "','newFilename':'" + newFilename + "'}"; 51 } 52 } 53 catch (Exception ex) 54 { 55 strErr = "{ 'error':'xxxxxx', 'msg':'错误','imgurl':'错误','newFilename':'错误'}"; 56 } 57 finally 58 { 59 context.Response.Write(strErr); 60 context.Response.End(); 61 } 62 } 63 64 65 }