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("导入失败");}}

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的文件上传相关推荐

  1. vue 项目 支持 ie9 实现文件上传

    最近在做的一个项目,需要兼容到ie9,其他功能都好实现,唯有文件上传这块,花费了挺长时间的,遇到了很多坑,现在整理一下 大家应该知道,element-ui和iview中的文件上传,是不支持ie9的 这 ...

  2. html+js实现音频上传并能播放(支持多个文件上传)

    html代码: <!DOCTYPE html> <html><head><meta charset="utf-8"><titl ...

  3. extjs 限制上传文件类型_如何让extjg 支持选择多文件上传

    2.添加渲染完组件后事件: ,supportMultFn: function($this){ //2.1 为input添加支持多文件选择属性 var typeArray = ["applic ...

  4. layui实现文件压缩上传_基于SSM框架、Layui的多文件上传、包括图片,压缩包,音频等文件(与数据库挂钩) - 爱秧博客...

    写在前面:当初为了实现一个多文件上传可是费了一番功夫,经过我日日夜夜的百度咨询,写了好几种方法,最终还是没能解决问题.我可以很负责任的告诉你,你去百度上不管你形容有多好,只要是涉及多文件,就会查到Mu ...

  5. 2014-07-23 利用ASP.NET自带控件实现单文件上传与下载

    效果图 上传文件页面: 下载文件页面:   1.母版页site.Master <%@ Master Language="C#" AutoEventWireup="t ...

  6. Java 文件上传下载管理器(控制台)

    文件上传下载管理器项目技术 JDBC + IO + Socket 实现功能 客户端注册:通过输入用户名,密码,确认密码并且校验完成以后将用户信息储存在数据库中. 客户端登录:通过输入用户名和密码到数据 ...

  7. 文件上传之Apache commons fileupload使用

    文件上传的方法主要目前有两个常用的,一个是SmartUpload,一个是Apache的Commons fileupload. 我们这里主要介绍下第二个的用法,首先要上传文件,注意几个问题: 1 for ...

  8. formdata多文件上传_如何使用FormData轻松上传单个或多个文件

    formdata多文件上传 In this post, we'll learn about the FormData interface available in modern web browser ...

  9. php中file对象实例,AJAX_File, FileReader 和 Ajax 文件上传实例分析(php),File FileReader 可以干什么? Ajax - phpStudy...

    File, FileReader 和 Ajax 文件上传实例分析(php) File FileReader 可以干什么?Ajax文件上传例子 FileReader 对象可以读取文件的 Base64编码 ...

  10. JavaWeb:实现文件上传与下载

    JavaWeb:实现文件上传与下载 文件上传前端处理 本模块使用到的前端Ajax库为Axio,其地址为GitHub官网. 关于文件上传 上传文件就是把客户端的文件发送给服务器端. 在常见情况(不包含文 ...

最新文章

  1. RTX 30系游戏本来了!1月26日开售,售价999美元起
  2. Linux Kernel中spinlock的设计与实现
  3. 2019年春季学期第四周作业
  4. vue-cli 上手
  5. 软件测试技术lab1 2017.3.13
  6. zookeeper基本操作
  7. JS-function-BOM(window,history,location,navigator,screen)
  8. Nginx的accept_mutex配置
  9. ICEFaces Note(7)
  10. 【学习笔记】离散数学(Discrete Math) - 证明 Proof 3
  11. python面向对象编程实例:烤地瓜
  12. 【单片机】51单片机使用总结
  13. 记账软件,预设收支类别、收支账户进行记账的方法
  14. 高德地图定位获取当前地址城市街道等详细信息(全部代码)
  15. 鲲鹏devkit(迁移 测试 性能分析) boostkit
  16. 计算机网络光纤工作原理,如何实现宽带上网?详细说明光纤网络的工作原理和架构!...
  17. hiredis的使用
  18. docker-comose搭建sonarqube 及 maven项目使用
  19. Python 千猫图,简单技术满足你的收集控
  20. html直角三角形怎么实现,CSS绘制三角形的实现代码(border法)

热门文章

  1. 中国城市统计年鉴中地级市面板数据(2000-2019年)
  2. github客户端教程
  3. 用python设计数独的心得体会_Python生成数独矩阵
  4. java双缓冲_java 双缓冲技术
  5. Python数据分析第二周总结
  6. webm格式转换mp4_将webm转换为mp4
  7. python二维码批量拼接,多张高清二维码批量拼接
  8. MPC5744p时钟模块
  9. centos 添加windows字体库
  10. 全文搜索引擎Solr原理和实战教程