标签:style blog http color io os 使用 java ar
弄了几天的上传,总是各种不兼容,现在基本算是完善了。目前的状况是发布在我自己的笔记本上,用同事的电脑访问IE10、firefox、chrome都可以正常上传,还有其他不完善的地方,欢迎大家赐教。。。。
ajaxfileupload.js
1 jQuery.extend({ 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 io; 17 var io = ‘<iframe id="‘ + frameId + ‘" name="‘ + frameId + ‘" style="position:absolute; top:-9999px; left:-9999px"‘; 18 if (window.ActiveXObject) { 19 if (typeof uri == ‘boolean‘) { 20 io += ‘ src="‘ + ‘javascript:false‘ + ‘"‘; 21 } 22 else if (typeof uri == ‘string‘) { 23 io += ‘ src="‘ + uri + ‘"‘; 24 } 25 } 26 io += ‘ />‘; 27 $(document.body).append($(io)); 28 29 return jQuery("#" + frameId).get(0); 30 }, 31 createUploadForm: function (id, fileElementId, data) { 32 //create form 33 var formId = ‘jUploadForm‘ + id; 34 var fileId = ‘jUploadFile‘ + id; 35 var form = jQuery(‘<form action="" method="POST" name="‘ + formId + ‘" id="‘ + formId + ‘" enctype="multipart/form-data"></form>‘); 36 if (data) { 37 for (var i in data) { 38 jQuery(‘<input type="hidden" name="‘ + i + ‘" value="‘ + data[i] + ‘" />‘).appendTo(form); 39 } 40 } 41 var oldElement = jQuery(‘#‘ + fileElementId); 42 var newElement = jQuery(oldElement).clone(); 43 jQuery(oldElement).attr(‘id‘, fileId); 44 jQuery(oldElement).before(newElement); 45 jQuery(oldElement).appendTo(form); 46 47 48 49 //set attributes 50 jQuery(form).css(‘position‘, ‘absolute‘); 51 jQuery(form).css(‘top‘, ‘-1200px‘); 52 jQuery(form).css(‘left‘, ‘-1200px‘); 53 jQuery(form).appendTo(‘body‘); 54 return form; 55 }, 56 57 ajaxFileUpload: function (s) { 58 // TODO introduce global settings, allowing the client to modify them for all requests, not only timeout 59 s = jQuery.extend({}, jQuery.ajaxSettings, s); 60 var id = new Date().getTime() 61 var form = jQuery.createUploadForm(id, s.fileElementId, (typeof (s.data) == ‘undefined‘ ? false : s.data)); 62 var io = jQuery.createUploadIframe(id, s.secureuri); 63 var frameId = ‘jUploadFrame‘ + id; 64 var formId = ‘jUploadForm‘ + id; 65 // Watch for a new set of requests 66 if (s.global && !jQuery.active++) { 67 jQuery.event.trigger("ajaxStart"); 68 } 69 var requestDone = false; 70 // Create the request object 71 var xml = {} 72 if (s.global) 73 jQuery.event.trigger("ajaxSend", [xml, s]); 74 // Wait for a response to come back 75 var uploadCallback = function (isTimeout) { 76 var io = document.getElementById(frameId); 77 try { 78 if (io.contentWindow) { 79 xml.responseText = io.contentWindow.document.body ? io.contentWindow.document.body.innerHTML : null; 80 xml.responseXML = io.contentWindow.document.XMLDocument ? io.contentWindow.document.XMLDocument : io.contentWindow.document; 81 82 } else if (io.contentDocument) { 83 xml.responseText = io.contentDocument.document.body ? io.contentDocument.document.body.innerHTML : null; 84 xml.responseXML = io.contentDocument.document.XMLDocument ? io.contentDocument.document.XMLDocument : io.contentDocument.document; 85 } 86 } catch (e) { 87 debugger; 88 jQuery.handleError(s, xml, null, e); 89 } 90 if (xml || isTimeout == "timeout") { 91 requestDone = true; 92 var status; 93 try { 94 status = isTimeout != "timeout" ? "success" : "error"; 95 // Make sure that the request was successful or notmodified 96 if (status != "error") { 97 // process the data (runs the xml through httpData regardless of callback) 98 var data = jQuery.uploadHttpData(xml, s.dataType); 99 // If a local callback was specified, fire it and pass it the data 100 if (s.success) 101 s.success(data, status); 102 103 // Fire the global callback 104 if (s.global) 105 jQuery.event.trigger("ajaxSuccess", [xml, s]); 106 } else 107 jQuery.handleError(s, xml, status); 108 } catch (e) { 109 status = "error"; 110 jQuery.handleError(s, xml, status, e); 111 } 112 113 // The request was completed 114 if (s.global) 115 jQuery.event.trigger("ajaxComplete", [xml, s]); 116 117 // Handle the global AJAX counter 118 if (s.global && ! --jQuery.active) 119 jQuery.event.trigger("ajaxStop"); 120 121 // Process result 122 if (s.complete) 123 s.complete(xml, status); 124 125 jQuery(io).unbind() 126 127 setTimeout(function () { 128 try { 129 jQuery(io).remove(); 130 jQuery(form).remove(); 131 132 } catch (e) { 133 jQuery.handleError(s, xml, null, e); 134 } 135 136 }, 100) 137 138 xml = null 139 140 } 141 } 142 // Timeout checker 143 if (s.timeout > 0) { 144 setTimeout(function () { 145 // Check to see if the request is still happening 146 if (!requestDone) uploadCallback("timeout"); 147 }, s.timeout); 148 } 149 try { 150 151 var form = jQuery(‘#‘ + formId); 152 jQuery(form).attr(‘action‘, s.url); 153 jQuery(form).attr(‘method‘, ‘POST‘); 154 jQuery(form).attr(‘target‘, frameId); 155 if (form.encoding) { 156 jQuery(form).attr(‘encoding‘, ‘multipart/form-data‘); 157 } 158 else { 159 jQuery(form).attr(‘enctype‘, ‘multipart/form-data‘); 160 } 161 jQuery(form).submit(); 162 163 } catch (e) { 164 jQuery.handleError(s, xml, null, e); 165 } 166 167 jQuery(‘#‘ + frameId).load(uploadCallback); 168 return { abort: function () { } }; 169 170 }, 171 172 uploadHttpData: function (r, type) { 173 var data = !type; 174 data = type == "xml" || data ? r.responseXML : r.responseText; 175 // If the type is "script", eval it in global context 176 if (type == "script") 177 jQuery.globalEval(data); 178 // Get the JavaScript object, if JSON is used. 179 if (type == "json") 180 eval("data = " + data); 181 // evaluate scripts within html 182 if (type == "html") 183 jQuery("<div>").html(data).evalScripts(); 184 185 return data; 186 } 187 })
html代码:
1 <input type="text" id="txt_file" name="txt_file" class="inputstyle" readonly style="width: 70%" /> 2 <input type="button" id="btn_upload" name="btn_upload" class="btn_upload" value="选择文件" /> 3 <input type="file" id="file_Excel" name="file_Excel" class="filestyle" style="width: 90%; display: none;" onchange="ajaxFileUpload();" />
js代码:
1 $(function(){ 2 $("body").delegate("#btn_upload", "click", function () {
$("#file_Excel").trigger("click");
});
5 }); 6 7 8 function ajaxFileUpload() { 9 // var filename = getFilePath($("#file_Excel").get(0)); // 本来在网上找了一个获取file路径的方法,但是好像都不怎么管用,最后还是直接取value值了 10 var filename = $("#file_Excel").val(); 11 var suffix = filename.substring(filename.lastIndexOf(‘.‘), filename.length - 1); 12 if (filename == ‘‘ || filename == undefined) { 13 alert(‘请选择需要上传的文件!‘); 14 return false; 15 } 16 if (suffix != ‘.xls‘ && suffix != ‘.xlsx‘ && suffix != ‘.csv‘) { 17 alert(‘请选择正确的文件格式(.xls|.xlsx|.csv)!‘); 18 return false; 19 } 20 $("#txt_file").val(filename); 21 22 $.ajaxFileUpload({ 23 url: ‘../ASHX/BBISExcelImportSample.ashx‘, // 请求URL地址
24 type: ‘POST‘, 25 data: { 26 type: ‘getExcelInfo‘, 29 rnd: Math.random().toString() 30 }, // 自定义参数
31 secureuri: false, // 默认false
32 fileElementId: ‘file_Excel‘, // 页面上file控件的ID,控件要有name属性
33 dataType: ‘JSON‘, // 请求成功之后返回的数据格式
34 success: function (data) { // 请求成功之后回调函数 35 }, 36 error: function (XMLHttpRequest, textStatus, errorTHrown) {// 请求报错之后执行 37 } 38 }); 39 }
C#代码:
1 public void ProcessRequest(HttpContext context) 2 { 3 string result = string.Empty; 4 if (!String.IsNullOrEmpty(context.Request.Form["type"])) 5 { 6 string type = context.Request.Form["type"]; 7 switch (type) 8 { 9 case "getExcelInfo": 10 result = GetExcelInfo(); 11 break; 12 default: 13 break; 14 } 15 } 16 context.Response.Write(result); 17 context.Response.End(); 18 } 19 20 21 #region 获取EXCEL相关信息 22 private string GetExcelInfo() 23 { 24 string result = string.Empty; 25 result = "{"; 26 HttpFileCollection files = HttpContext.Current.Request.Files; 27 string filename = files[0].FileName; 28 string sheetName = HttpContext.Current.Request.Form["sheetName"]; 29 string template_id = HttpContext.Current.Request.Form["template_id"]; 30 31 WebApp.DataTableRenderToExcel.FilePath = filename; 32 WebApp.DataTableRenderToExcel.SheetName = sheetName; 33 // 获取工作簿Sheet集合 34 List<string> sheetList = WebApp.DataTableRenderToExcel.ExcelSheetToDT(); 35 // 获取EXCEL表头 36 DataTable dt_columns = WebApp.DataTableRenderToExcel.GetExcelHeader(); 37 // 获取EXCEL数据 38 DataTable dt_data = WebApp.DataTableRenderToExcel.GetExcelData(); 39 result += "\"sheet\":" + JsonConvert.SerializeObject(sheetList); 40 result += ",\"columns\":" + JsonConvert.SerializeObject(dt_columns); 41 result += ",\"excelData\":" + JsonConvert.SerializeObject(dt_data); 42 if (sheetList != null) sheetList = null; 43 if (dt_columns != null) dt_columns.Dispose(); 44 if (dt_columns != null) dt_columns = null; 45 if (dt_data != null) dt_data.Dispose(); 46 if (dt_data != null) dt_data = null; 47 48 result += "}"; 49 return result; 50 } 51 #endregion
记录下来,一是为了方便下次使用,另外也希望对大家有所帮助。。
标签:style blog http color io os 使用 java ar
原文地址:http://www.cnblogs.com/luole/p/3964831.html