考虑浏览器兼容的文件上传(IE8不支持FormData)
方法一:使用FormData(因IE8不支持FormData, IE10才支持,因此此方法不兼容IE10以下的IE浏览器)
也可参考文章 http://www.jianshu.com/p/46e6e03a0d53
html:
- <input type="file" class="form-control" id="inputfile" title="多个文件请打包后再上传" style="display:inline-block;width:100%;_overflow:hidden;" />
js:
- //新增行的保存及上传文件
- function uploadFile(data) {
- var fileObj = document.getElementById("inputfile").files; // js 获取文件对象
- var FileController = "/action/add"; // 接收上传文件的后台地址
- var form = new FormData();
- //20160301 添加其他参数
- form.append("param1",param1);
- form.append("param2",param2);
- if (fileObj.length != 0) {
- var i = fileObj.length;
- for (var j = 0; j < i; j++) {
- form.append("file" + j, fileObj[j]); // 文件对象
- }
- }
- form.append("data", data);
- // XMLHttpRequest 对象
- xmlHttpRequest = new XMLHttpRequest();
- xmlHttpRequest.onreadystatechange = callback;
- xmlHttpRequest.open("post", FileController, true);
- /* event listeners */
- // 进度条
- // xmlHttpRequest.upload.addEventListener("progress", progressFunction, false);
- // xmlHttpRequest.addEventListener("load", uploadComplete, false);
- // xmlHttpRequest.addEventListener("error", uploadFailed, false);
- // xmlHttpRequest.addEventListener("abort", uploadCanceled, false);
- /* end listeners */
- xmlHttpRequest.send(form);
- }
- function callback() {
- // 接收响应数据
- // 判断对象状态是否交互完成,如果为4则交互完成
- if (xmlHttpRequest.readyState == 4) {
- // 判断对象状态是否交互成功,如果成功则为200
- if (xmlHttpRequest.status == 200) {
- // 接收数据,得到服务器输出的纯文本数据
- var response = xmlHttpRequest.responseText;
- //console.log(response);
- if(response == 1) {
- enabledButton();
- alert("保存成功!");
- } else {
- alert("保存失败,请重新尝试!");
- }
- enableButton();
- }else{//!=200
- alert("保存失败!");
- enableButton();
- }
- }
- }
方法二:使用form提交 兼容各种浏览器,form提交后会刷新页面,且不太好获取返回参数。如要返回原始页面,需要用response.sendRedirect(原始页面url)
进行转向。
html:
- <form id="uploadFileForm" name="uploadFileForm" enctype="multipart/form-data" method="post">
- <input type="hidden" id="param1" name="param1" value="123"/>
- <input type="hidden" id="param2" name="param2" value="测试参数"/>
- <div id="uploadFileTableDiv" style="margin-left:10%;">
- <table border="1" width="80%">
- <tr>
- <td style="padding:10px;">
- <span style="float:left;">上传文件: </span>
- </td>
- <td style="padding:10px;">
- <input type="file" id="attach" name="attach" size="25" style="height:30px;" />
- </td>
- </tr>
- <tr>
- <td colspan="2" style="padding:10px;padding-left:50px;">
- <button id="submit_btn" type="button" class="btn btn-default" onclick="javascript:submitFile();">
- 上传文件
- </button>
- </td>
- </tr>
- </table>
- </div>
- </form>
js:
- //20160612 文件上传按钮 form表单提交
- function submitFile(){
- var attach = document.getElementById("attach").value;
- alert("attach: " + attach);
- if(attach == undefined || attach == ""){
- alert("请选择文件");
- return;
- }
- uploadFileForm.action = "/tools/uploadFileAction";
- uploadFileForm.submit();
- }
方法三:使用jquery.form.js支持的ajaxsubmit进行文件上传
htm
- <script th:src="@{/jquery/3.46.0/jquery.form.js}"></script>
- <form id="uploadFileForm2" name="uploadFileForm2" enctype="multipart/form-data" method="post">
- <div id="uploadFileTableDiv2" style="margin-left:10%;">
- <table border="1" width="80%">
- <tr>
- <td style="padding:10px;">
- <span style="float:left;">上传文件: </span>
- </td>
- <td style="padding:10px;">
- <input type="file" id="attach2" name="attach2" size="25" style="height:30px;" />
- </td>
- </tr>
- <tr>
- <td colspan="2" style="padding:10px;padding-left:50px;">
- <button id="submit_btn2" type="button" class="btn btn-default" onclick="javascript:ajaxSubmitFile();">
- 上传文件
- </button>
- </td>
- </tr>
- </table>
- </div>
- </form>
js:
- //在表单上追加input hidden元素 存放其他参数
- function appendInputElementForForm(formId,inputName,inputValue){
- var myh = document.createElement("input");
- myh.type = "hidden";
- myh.value = inputValue;
- myh.id = inputName;
- myh.name = inputName;
- document.getElementById(formId).appendChild(myh);
- alert(document.getElementById(inputName).value);
- }
- //20170207 文件上传ajax Form表单提交
- function ajaxSubmitFile(){
- var attach = document.getElementById("attach2").value;
- alert("ajaxSubmitFile attach2: " + attach);
- if(attach == undefined || attach == ""){
- alert("请选择文件");
- return;
- }
- appendInputElementForForm( "uploadFileForm2", "param1", "123");
- appendInputElementForForm( "uploadFileForm2", "param2", "测试参数");
- $('#uploadFileForm2').ajaxSubmit({
- type:"post",
- url:"/tools/ajaxUploadFileAction",
- data:$('#uploadFileForm2').serialize(),
- dataType:"json",
- error:function(data){
- alert(data);
- },
- success:function(data){
- alert("ajaxSubmit上传成功");
- alert("下载地址: " + data.data.attachment);
- }
- });
- }
最后附带上后台的java代码:
- //20160612 文件上传
- @RequestMapping(value = "ajaxUploadFileAction")
- public ModelAndView ajaxUploadFile(HttpServletRequest request, HttpServletResponse response) throws Exception{
- ResponseInfo responseInfo = new ResponseInfo();
- logger.info("ajaxUploadFile param1: " + request.getParameter("param1"));
- logger.info("ajaxUploadFile param2: " + request.getParameter("param2"));
- try {
- //将当前上下文初始化给CommonsMutipartResolver (多部分解析器)
- CommonsMultipartResolver multipartResolver=new CommonsMultipartResolver( request.getSession().getServletContext());
- // 判断是否是多数据段提交格式
- if (multipartResolver.isMultipart(request)) {
- MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest)request;
- logger.info("ajaxUploadFile param1: " + multiRequest.getParameter("param1"));
- logger.info("ajaxUploadFile param2: " + multiRequest.getParameter("param2"));
- Iterator<String> iter = multiRequest.getFileNames();
- logger.info("iter.hasNext(): "+iter.hasNext());
- Integer fileCount = 0;
- while (iter.hasNext()) {
- MultipartFile multipartFile = multiRequest.getFile(iter.next());
- String fileName = multipartFile.getOriginalFilename();
- logger.info("upload demand filename: " + fileName );
- //20170207 针对IE环境下filename是整个文件路径的情况而做以下处理
- Integer index = fileName.lastIndexOf("\\");
- String newStr = "";
- if(index>-1){
- newStr = fileName.substring(index+1);
- }else{
- newStr = fileName;
- }
- if(!newStr.equals("")){
- fileName = newStr;
- }
- logger.info("new filename: " + fileName );
- if (multipartFile != null) {
- HashMap<String,Object> result = DispatchInterfaceUtil.uploadFileByInputStream (multipartFile.getInputStream(),multipartFile.getSize(),fileName);
- Integer statusCode = (Integer)result.get("statusCode");
- logger.info("statusCode: " + statusCode);
- if( statusCode.equals(0) ){
- String attachment = (String)result.get("attachment");
- responseInfo. setStatus(true);
- responseInfo.put("attachment", attachment);
- }else{
- String errorMessage = (String)result.get("errorMessage");
- logger.error( "errorMessage: " + errorMessage);
- responseInfo.setStatus(false);
- responseInfo.setMsg("文件上传失败");
- }
- }
- fileCount++;
- }//while
- logger.info("fileCount: " + fileCount);
- }
- }catch (Exception e) {
- // TODO: handle exception
- responseInfo.setStatus(false);
- responseInfo.setMsg("后台出现异常");
- logger.warn("Error: ", e);
- }
- response.setContentType("text/html; charset=utf-8");
- response.getWriter().write( JSON.toJSONString(responseInfo));
- return null;
- }
注意:
(1)IE10可以支持application/json格式的Response了,也就是说低于IE10版本一下的IE浏览器都需要使用text/html格式的Response。 在Response头中指定Content-Type为text/html,是可以解决问题的。这样返回给客户端的是一个JSON字符串(并非JSON对象),无需IE来解析。
(2)通过js动态添加的input file元素是无法通过form submit的方式(如上所述的后两种方法)将文件内容提交给后台进行文件上传的,因为后台服务器根本不知道有此元素. 若需要动态添加,可以先在html页面中添加上不可见的input file元素(这样后台服务器就知道了该元素的存在), 需要添加时再通过js语句 document.getElementById(父元素ID).appendChild(inputFile元素对象)
将input file对象添加在适当位置
(3)在$.each代码块内不能使用break和continue,要实现break和continue的功能的话,要使用其它的方式:
break—-用return false;
continue –用return true;
考虑浏览器兼容的文件上传(IE8不支持FormData)的更多相关文章
- 表单多文件上传样式美化 && 支持选中文件后删除相关项
开发中会经常涉及到文件上传的需求,根据业务不同的需求,有不同的文件上传情况. 有简单的单文件上传,有多文件上传,因浏览器原生的文件上传样式及功能的支持度不算太高,很多时候我们会对样式进行美化,对功能进 ...
- Nginx集群之WCF大文件上传及下载(支持6G传输)
目录 1 大概思路... 1 2 Nginx集群之WCF大文件上传及下载... 1 3 BasicHttpBinding相关配置解析... 2 4 编写 ...
- jquery.form 兼容IE89文件上传
导入部分 <script type="text/javascript" src="js/jquery-1.8.3.min.js" charset=&quo ...
- JS_单个或多个文件上传_不支持单独修改
A-From表单直接填写提交地址,不过干预: 1. 单文件上传 最简单的文件上传,是单文件上传,form标签中加入enctype="multipart/form-data",for ...
- html多文件上传,可支持预览
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8&quo ...
- ajaxfileupload多文件上传 - 修复只支持单个文件上传的bug
搜索: jquery ajaxFileUpload AjaxFileUpload同时上传多个文件 原生的AjaxFileUpload插件是不支持多文件上传的,通过修改AjaxFileUpload少量代 ...
- AngularJs 文件上传(实现Multipart/form-data 文件的上传)
<!-- 上传yml文件 --> <div class="blackBoard" ng-show="vm.showUpop==true"> ...
- JS实现表单多文件上传样式美化支持选中文件后删除相关项
http://www.youdaili.net/javascript/5903.html
- Servlet3.0学习总结——基于Servlet3.0的文件上传
Servlet3.0学习总结(三)——基于Servlet3.0的文件上传 在Servlet2.5中,我们要实现文件上传功能时,一般都需要借助第三方开源组件,例如Apache的commons-fileu ...
随机推荐
- 基于MMSE的预测
本文的目的是预测随机变量的输出值. 既然有预测值,那么我们就需要一个判断基准(criterion)用于判断该预测值与该随机变量的实际输出之间的差值,这里采用的判断基准就是MSE(mean-square ...
- 【Python】Python-Numpy教程
Numpy的使用 读txt数据: · genfromtxt import numpy as np print(help(np.genfromtxt)) #data = np.genfromtxt(&q ...
- 日期T转换
日期转换 在startup.csd ConfigureServices方法里 services.AddMvc().AddJsonOptions(o => { o.SerializerSettin ...
- luogu P1077 摆花
这道题看似好难,但是其实很简单 先把题目中所让你设的变量都设好,该输入的都输入 你会发现这道题好像成功了一半,为什么呢??? 因为设完后你会发现你不需要再添加任何变量,已经足够了. 可能最难的地方,就 ...
- 2018-01微信小程序--直播
一. 小程序直播支持的格式 目前小程序支付两种格式直播 1) flv格式直播 2) rtmp格式直播 二. 能够开通小程序直播的行业类目 由于直播需要资质, 并不是每个企业都能够开通小程序直播, 微信 ...
- JAVA 获取指定网址的IP地址 实例
如今买票是一大难事,在高峰时段 打开12306网站,慢的像蜗牛,想到以前用修改hosts文件来登录Google(Hosts是一个没有扩展名的系统文件,可以用记事本等工具打开,其作用就是将一些常用的网址 ...
- 【BZOJ5287】[HNOI2018]毒瘤(动态规划,容斥)
[BZOJ5287][HNOI2018]毒瘤(动态规划,容斥) 题面 BZOJ 洛谷 题解 考场上想到的暴力做法是容斥: 因为\(m-n\le 10\),所以最多会多出来\(11\)条非树边. 如果就 ...
- [2017-7-28]Android Learning Day7
View动画效果 透明动画效果 旋转动画效果 移动动画效果 缩放动画效果 混合动画效果 1.透明动画效果(AlphaAnimation) 有两种方法 第一种在活动中设置,不需要xml文件 public ...
- 使用BlockQueue实现生产者和消费者模式
数据 package cn.lonecloud.procum; /** * @author lonecloud * @version v1.0 * @date 上午11:00 2018/5/7 */ ...
- javascript之复习(框架里的方法们)
继上次整理,一些东西没有整理完.就写在这.可能比较乱比较杂,因为都是整理的一些东西,也没有到做成专题的程度. 1.String.repeat() 大家要实现重复一个字符串的重复怎么写呢,反正我的第一想 ...