日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當(dāng)前位置: 首頁(yè) > 编程资源 > 编程问答 >内容正文

编程问答

支持IE8的文件上传

發(fā)布時(shí)間:2023/12/10 编程问答 37 豆豆
生活随笔 收集整理的這篇文章主要介紹了 支持IE8的文件上传 小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
1.依附于用了jquery所以需要先導(dǎo)包,然后添加這一個(gè)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.前臺(tái)的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">批量導(dǎo)入注意事項(xiàng):表頭順序等信息請(qǐng)參照模版,導(dǎo)入完成需下載EXCEL文件查看導(dǎo)入反饋信息!</div>2.2.頁(yè)面上的js代碼如下:
//批量導(dǎo)入方法function do_Excel(){$.messager.confirm("導(dǎo)入確認(rèn)","導(dǎo)入時(shí)間可能會(huì)很長(zhǎng),請(qǐng)耐心等待,請(qǐng)勿做其他操作!",function (res) {if (res) {var path = $("#user_file").val();//文件全稱if(path=="" || path==null){$.messager.alert("系統(tǒng)提示","請(qǐng)上傳文件后再導(dǎo)入!","info");return ;}var suffix = path.substring(path.lastIndexOf("."));//文件后綴名var allowedSuffix = ".xlsx、.xls";if(allowedSuffix.indexOf(suffix) < 0){//校驗(yàn)上傳文件的類型$.messager.alert("系統(tǒng)提示","請(qǐng)上傳后綴為【"+ allowedSuffix +"】的文件","info");return ;}$.ajaxFileUpload({url: '。。。',//用于文件上傳的服務(wù)器端請(qǐng)求地址secureuri: false,//一般設(shè)置為falsefileElementId: 'user_file', //文件上傳空間的id屬性 <input type="file" id="file" name="file" />dataType: 'JSON',//返回值類型 一般設(shè)置為json,大寫data: {},type: 'post',success: function(result,status){//服務(wù)器成功響應(yīng)處理函數(shù)var data = $.parseJSON(result);//json對(duì)象的反序列化if(data.stat == "1") {$('#id').window('close');$.messager.alert("系統(tǒng)提示",data.message,"info");//下載返回模板var fileName = data.data;var downloadUrl = "。。。";jQuery('<form action="'+downloadUrl+'" method="'+('post')+'">' + // action請(qǐng)求路徑及推送方法'<input type="text" name="fileName" value="'+fileName+'"/>' + // 文件名稱'</form>').appendTo('body').submit().remove();}else{$.messager.alert("系統(tǒng)提示",data.message,"info");}// 隱藏遮罩$.messager.progress('close');}});}});}3.后臺(tái)接收文件的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();//接收數(shù)據(jù)Workbook workbook = null;if (suffix.equals(".xls")) {//2003版之前表格workbook = new HSSFWorkbook(is);} else {//XSSFWorkbook用來(lái)解析2007之后的版本(xlsx)workbook = new XSSFWorkbook(is);}Sheet sheet = workbook.getSheetAt(0);//批量導(dǎo)入的excel文件的數(shù)據(jù)String fileName = "處理自己的邏輯";return ResultData.success("導(dǎo)入成功",fileName).toJson();}catch (Exception e) {e.printStackTrace();return ResultData.failureToJson("導(dǎo)入失敗");}} else {return ResultData.failureToJson("導(dǎo)入失敗");}}

4.附帶文件下載的java后臺(tái)代碼,前臺(tái)不能用ajax發(fā)送請(qǐng)求,可以模擬表單提交或者用超鏈接

public void downloadTemp(HttpServletRequest request, HttpServletResponse response,@RequestParam(value = "fileName",required = false) String fileName) {//獲取項(xiàng)目的根目錄下的指定目錄String path = request.getSession().getServletContext().getRealPath("/") + File.separator + "Excel" + File.separator;if (Empty.isEmpty(fileName)) {//為空時(shí)下載模板,或者前臺(tái)傳入的文件名參數(shù)為空時(shí)也會(huì)下載模板path += "模板名稱.xls";} else {//不為空時(shí)下載反饋文件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");//針對(duì)IE或者以IE為內(nèi)核的瀏覽器: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();}}}//刪除導(dǎo)入時(shí)存放的零時(shí)文件,fileName零時(shí)文件名if (Empty.isNotEmpty(fileName)) {if (file.exists()) {file.delete();}}}


總結(jié)

以上是生活随笔為你收集整理的支持IE8的文件上传的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。