支持IE8的文件上传
生活随笔
收集整理的這篇文章主要介紹了
支持IE8的文件上传
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
1.依附于用了jquery所以需要先導包,然后添加這一個js文件代碼如下:
jQuery.extend({createUploadIframe: function(id, uri){//create framevar frameId = 'jUploadFrame' + id;/* if(window.ActiveXObject) {var io = document.createElement('<iframe id="' + frameId + '" name="' + frameId + '" />');if(typeof uri== 'boolean'){io.src = 'javascript:false';}else if(typeof uri== 'string'){io.src = uri;}}*/if(window.ActiveXObject) { //修改以后的代碼if(jQuery.browser.version=="9.0" || jQuery.browser.version=="10.0"){ var io = document.createElement('iframe'); io.id = frameId; io.name = frameId; }else if(jQuery.browser.version=="6.0" || jQuery.browser.version=="7.0" || jQuery.browser.version=="8.0"){ var io = document.createElement('<iframe id="' + frameId + '" name="' + frameId + '" />'); if(typeof uri== 'boolean'){ io.src = 'javascript:false'; } else if(typeof uri== 'string'){ io.src = uri; } } } //修改以后的代碼else {var io = document.createElement('iframe');io.id = frameId;io.name = frameId;}io.style.position = 'absolute';io.style.top = '-1000px';io.style.left = '-1000px';document.body.appendChild(io);return io},createUploadForm: function(id, fileElementId){//create formvar formId = 'jUploadForm' + id;var fileId = 'jUploadFile' + id;var form = $('<form action="" method="POST" name="' + formId + '" id="' + formId + '" enctype="multipart/form-data"></form>');var oldElement = $('#' + fileElementId);var newElement = $(oldElement).clone();$(oldElement).attr('id', fileId);$(oldElement).before(newElement);$(oldElement).appendTo(form);//set attributes$(form).css('position', 'absolute');$(form).css('top', '-1200px');$(form).css('left', '-1200px');$(form).appendTo('body');return form;},addOtherRequestsToForm: function(form,data){// add extra parametervar originalElement = $('<input type="hidden" name="" value="">');for (var key in data) {name = key;value = data[key];var cloneElement = originalElement.clone();cloneElement.attr({'name':name,'value':value});$(cloneElement).appendTo(form);}return form;},ajaxFileUpload: function(s) {// TODO introduce global settings, allowing the client to modify them for all requests, not only timeouts = jQuery.extend({}, jQuery.ajaxSettings, s);var id = new Date().getTime()var form = jQuery.createUploadForm(id, s.fileElementId);if ( s.data ) form = jQuery.addOtherRequestsToForm(form,s.data);var io = jQuery.createUploadIframe(id, s.secureuri);var frameId = 'jUploadFrame' + id;var formId = 'jUploadForm' + id;// Watch for a new set of requestsif ( s.global && ! jQuery.active++ ){jQuery.event.trigger( "ajaxStart" );}var requestDone = false;// Create the request objectvar xml = {}if ( s.global )jQuery.event.trigger("ajaxSend", [xml, s]);// Wait for a response to come backvar uploadCallback = function(isTimeout){var io = document.getElementById(frameId);try{if(io.contentWindow){xml.responseText = io.contentWindow.document.body?io.contentWindow.document.body.innerHTML:null;xml.responseXML = io.contentWindow.document.XMLDocument?io.contentWindow.document.XMLDocument:io.contentWindow.document;}else if(io.contentDocument){xml.responseText = io.contentDocument.document.body?io.contentDocument.document.body.innerHTML:null;xml.responseXML = io.contentDocument.document.XMLDocument?io.contentDocument.document.XMLDocument:io.contentDocument.document;}}catch(e){jQuery.handleError(s, xml, null, e);}if ( xml || isTimeout == "timeout"){requestDone = true;var status;try {status = isTimeout != "timeout" ? "success" : "error";// Make sure that the request was successful or notmodifiedif ( status != "error" ){// process the data (runs the xml through httpData regardless of callback)var data = jQuery.uploadHttpData( xml, s.dataType );// If a local callback was specified, fire it and pass it the dataif ( s.success )s.success( data, status );// Fire the global callbackif( s.global )jQuery.event.trigger( "ajaxSuccess", [xml, s] );} elsejQuery.handleError(s, xml, status);} catch(e){status = "error";jQuery.handleError(s, xml, status, e);}// The request was completedif( s.global )jQuery.event.trigger( "ajaxComplete", [xml, s] );// Handle the global AJAX counterif ( s.global && ! --jQuery.active )jQuery.event.trigger( "ajaxStop" );// Process resultif ( s.complete )s.complete(xml, status);jQuery(io).unbind()setTimeout(function(){ try{$(io).remove();$(form).remove();} catch(e){jQuery.handleError(s, xml, null, e);}}, 100)xml = null}}// Timeout checkerif ( s.timeout > 0 ){setTimeout(function(){// Check to see if the request is still happeningif( !requestDone ) uploadCallback( "timeout" );}, s.timeout);}try{// var io = $('#' + frameId);var form = $('#' + formId);$(form).attr('action', s.url);$(form).attr('method', 'POST');$(form).attr('target', frameId);if(form.encoding){form.encoding = 'multipart/form-data';}else{form.enctype = 'multipart/form-data';}$(form).submit();} catch(e){jQuery.handleError(s, xml, null, e);}if(window.attachEvent){document.getElementById(frameId).attachEvent('onload', uploadCallback);}else{document.getElementById(frameId).addEventListener('load', uploadCallback, false);}return {abort: function () {}};},uploadHttpData: function( r, type ) {var data = !type;data = type == "xml" || data ? r.responseXML : r.responseText;// If the type is "script", eval it in global contextif ( type == "script" )jQuery.globalEval( data );// Get the JavaScript object, if JSON is used.if ( type == "json" ){// If you add mimetype in your response,// you have to delete the '<pre></pre>' tag.// The pre tag in Chrome has attribute, so have to use regex to removevar data = r.responseText;var rx = new RegExp("<pre.*?>(.*?)</pre>","i");var am = rx.exec(data);//this is the desired data extractedvar data = (am) ? am[1] : ""; //the only submatch or emptyeval( "data = " + data );}// evaluate scripts within htmlif ( type == "html" )jQuery("<div>").html(data).evalScripts();//alert($('param', data).each(function(){alert($(this).attr('value'));}));return data;}
})2.1.前臺的html代碼片段如下:
<div class="pM-m-formCell" style = "margin-left: 15px"><input type="file" name="impFile" id="user_file" style="width:200px"></div><div class="pM-m-formCell" style = "margin-left: 15px;margin-right: 15px">批量導入注意事項:表頭順序等信息請參照模版,導入完成需下載EXCEL文件查看導入反饋信息!</div>2.2.頁面上的js代碼如下:
//批量導入方法function do_Excel(){$.messager.confirm("導入確認","導入時間可能會很長,請耐心等待,請勿做其他操作!",function (res) {if (res) {var path = $("#user_file").val();//文件全稱if(path=="" || path==null){$.messager.alert("系統提示","請上傳文件后再導入!","info");return ;}var suffix = path.substring(path.lastIndexOf("."));//文件后綴名var allowedSuffix = ".xlsx、.xls";if(allowedSuffix.indexOf(suffix) < 0){//校驗上傳文件的類型$.messager.alert("系統提示","請上傳后綴為【"+ allowedSuffix +"】的文件","info");return ;}$.ajaxFileUpload({url: '。。。',//用于文件上傳的服務器端請求地址secureuri: false,//一般設置為falsefileElementId: 'user_file', //文件上傳空間的id屬性 <input type="file" id="file" name="file" />dataType: 'JSON',//返回值類型 一般設置為json,大寫data: {},type: 'post',success: function(result,status){//服務器成功響應處理函數var data = $.parseJSON(result);//json對象的反序列化if(data.stat == "1") {$('#id').window('close');$.messager.alert("系統提示",data.message,"info");//下載返回模板var fileName = data.data;var downloadUrl = "。。。";jQuery('<form action="'+downloadUrl+'" method="'+('post')+'">' + // action請求路徑及推送方法'<input type="text" name="fileName" value="'+fileName+'"/>' + // 文件名稱'</form>').appendTo('body').submit().remove();}else{$.messager.alert("系統提示",data.message,"info");}// 隱藏遮罩$.messager.progress('close');}});}});}3.后臺接收文件的Java代碼,如下: public JSON impTagUsers(@RequestParam(value = "impFile", required = false) MultipartFile file, HttpServletRequest request) {if (Empty.isNotEmpty(file)) {//獲取文件的后綴名String originalFileName = file.getOriginalFilename();String suffix = originalFileName.substring(originalFileName.lastIndexOf("."));InputStream is = null; // 獲取輸入文件流try {is = file.getInputStream();//接收數據Workbook workbook = null;if (suffix.equals(".xls")) {//2003版之前表格workbook = new HSSFWorkbook(is);} else {//XSSFWorkbook用來解析2007之后的版本(xlsx)workbook = new XSSFWorkbook(is);}Sheet sheet = workbook.getSheetAt(0);//批量導入的excel文件的數據String fileName = "處理自己的邏輯";return ResultData.success("導入成功",fileName).toJson();}catch (Exception e) {e.printStackTrace();return ResultData.failureToJson("導入失敗");}} else {return ResultData.failureToJson("導入失敗");}}
//批量導入方法function do_Excel(){$.messager.confirm("導入確認","導入時間可能會很長,請耐心等待,請勿做其他操作!",function (res) {if (res) {var path = $("#user_file").val();//文件全稱if(path=="" || path==null){$.messager.alert("系統提示","請上傳文件后再導入!","info");return ;}var suffix = path.substring(path.lastIndexOf("."));//文件后綴名var allowedSuffix = ".xlsx、.xls";if(allowedSuffix.indexOf(suffix) < 0){//校驗上傳文件的類型$.messager.alert("系統提示","請上傳后綴為【"+ allowedSuffix +"】的文件","info");return ;}$.ajaxFileUpload({url: '。。。',//用于文件上傳的服務器端請求地址secureuri: false,//一般設置為falsefileElementId: 'user_file', //文件上傳空間的id屬性 <input type="file" id="file" name="file" />dataType: 'JSON',//返回值類型 一般設置為json,大寫data: {},type: 'post',success: function(result,status){//服務器成功響應處理函數var data = $.parseJSON(result);//json對象的反序列化if(data.stat == "1") {$('#id').window('close');$.messager.alert("系統提示",data.message,"info");//下載返回模板var fileName = data.data;var downloadUrl = "。。。";jQuery('<form action="'+downloadUrl+'" method="'+('post')+'">' + // action請求路徑及推送方法'<input type="text" name="fileName" value="'+fileName+'"/>' + // 文件名稱'</form>').appendTo('body').submit().remove();}else{$.messager.alert("系統提示",data.message,"info");}// 隱藏遮罩$.messager.progress('close');}});}});}3.后臺接收文件的Java代碼,如下: public JSON impTagUsers(@RequestParam(value = "impFile", required = false) MultipartFile file, HttpServletRequest request) {if (Empty.isNotEmpty(file)) {//獲取文件的后綴名String originalFileName = file.getOriginalFilename();String suffix = originalFileName.substring(originalFileName.lastIndexOf("."));InputStream is = null; // 獲取輸入文件流try {is = file.getInputStream();//接收數據Workbook workbook = null;if (suffix.equals(".xls")) {//2003版之前表格workbook = new HSSFWorkbook(is);} else {//XSSFWorkbook用來解析2007之后的版本(xlsx)workbook = new XSSFWorkbook(is);}Sheet sheet = workbook.getSheetAt(0);//批量導入的excel文件的數據String fileName = "處理自己的邏輯";return ResultData.success("導入成功",fileName).toJson();}catch (Exception e) {e.printStackTrace();return ResultData.failureToJson("導入失敗");}} else {return ResultData.failureToJson("導入失敗");}}
4.附帶文件下載的java后臺代碼,前臺不能用ajax發送請求,可以模擬表單提交或者用超鏈接
public void downloadTemp(HttpServletRequest request, HttpServletResponse response,@RequestParam(value = "fileName",required = false) String fileName) {//獲取項目的根目錄下的指定目錄String path = request.getSession().getServletContext().getRealPath("/") + File.separator + "Excel" + File.separator;if (Empty.isEmpty(fileName)) {//為空時下載模板,或者前臺傳入的文件名參數為空時也會下載模板path += "模板名稱.xls";} else {//不為空時下載反饋文件path += fileName;}File file = new File(path);FileInputStream in = null;BufferedOutputStream out = null;try {out = new BufferedOutputStream(response.getOutputStream());response.reset();//解決瀏覽器文件名中文亂碼兼容問題String repFileName = file.getName();String agent = request.getHeader("User-Agent");//針對IE或者以IE為內核的瀏覽器:if (agent.contains("MSIE") || agent.contains("Trident")) {repFileName = URLEncoder.encode(repFileName, "UTF-8");} else {repFileName = new String(repFileName.getBytes("UTF-8"), "ISO-8859-1");}response.setHeader("Content-disposition", String.format("attachment; filename=\"%s\"", repFileName));response.setContentType("application/ms-excel;charset=utf-8");response.setCharacterEncoding("UTF-8");in = new FileInputStream(file);int count = 0;byte[] buffer = new byte[1024];while ((count = in.read(buffer)) > 0) {out.write(buffer, 0, count);}out.flush();} catch (Exception e) {e.printStackTrace();} finally {if (in != null) {try {in.close();out.close();} catch (Exception e) {e.printStackTrace();}}}//刪除導入時存放的零時文件,fileName零時文件名if (Empty.isNotEmpty(fileName)) {if (file.exists()) {file.delete();}}}總結
以上是生活随笔為你收集整理的支持IE8的文件上传的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 蓝牙---AVRCP协议
- 下一篇: 可信计算 沈昌祥_沈昌祥院士:用主动免疫