ajaxfileupload多文件上传 - 修复只支持单个文件上传的bug
搜索:
jquery ajaxFileUpload
AjaxFileUpload同时上传多个文件
原生的AjaxFileUpload插件是不支持多文件上传的,通过修改AjaxFileUpload少量代码就能实现多文件同时上传
AjaxFileUpload插件修复前代码
jQuery.extend({
createUploadIframe: function(id, uri)
{
//create frame
var frameId = 'jUploadFrame' + id;
var iframeHtml = '<iframe id="' + frameId + '" name="' + frameId + '" style="position:absolute; top:-9999px; left:-9999px"';
if(window.ActiveXObject)
{
if(typeof uri== 'boolean'){
iframeHtml += ' src="' + 'javascript:false' + '"'; }
else if(typeof uri== 'string'){
iframeHtml += ' src="' + uri + '"'; }
}
iframeHtml += ' />';
jQuery(iframeHtml).appendTo(document.body); return jQuery('#' + frameId).get(0);
},
createUploadForm: function(id,fileElementId,data,fileElement)
{
//create form
var formId = 'jUploadForm' + id;
var fileId = 'jUploadFile' + id;
var form = jQuery('<form action="" method="POST" name="' + formId + '" id="' + formId + '" enctype="multipart/form-data"></form>');
if(data)
{
for(var i in data)
{
jQuery('<input type="hidden" name="' + i + '" value="' + data[i] + '" />').appendTo(form);
}
}
var oldElement;
if(fileElement == null)
oldElement = jQuery('#' + fileElementId);
else
oldElement = fileElement; var newElement = jQuery(oldElement).clone();
jQuery(oldElement).attr('id', fileId);
jQuery(oldElement).before(newElement);
jQuery(oldElement).appendTo(form); //set attributes
jQuery(form).css('position', 'absolute');
jQuery(form).css('top', '-1200px');
jQuery(form).css('left', '-1200px');
jQuery(form).appendTo('body');
return form;
}, ajaxFileUpload: function(s) {
// TODO introduce global settings, allowing the client to modify them for all requests, not only timeout
s = jQuery.extend({}, jQuery.ajaxSettings, s);
var id = new Date().getTime()
var form = jQuery.createUploadForm(id, s.fileElementId, (typeof(s.data)=='undefined'?false:s.data),s.fileElement);
var io = jQuery.createUploadIframe(id, s.secureuri);
var frameId = 'jUploadFrame' + id;
var formId = 'jUploadForm' + id;
// Watch for a new set of requests
if ( s.global && ! jQuery.active++ )
{
jQuery.event.trigger( "ajaxStart" );
}
var requestDone = false;
// Create the request object
var xml = {}
if ( s.global )
jQuery.event.trigger("ajaxSend", [xml, s]);
// Wait for a response to come back
var 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 notmodified
if ( 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 data
if ( s.success )
s.success( data, status ); // Fire the global callback
if( s.global )
jQuery.event.trigger( "ajaxSuccess", [xml, s] );
} else
jQuery.handleError(s, xml, status);
} catch(e)
{
status = "error";
jQuery.handleError(s, xml, status, e);
} // The request was completed
if( s.global )
jQuery.event.trigger( "ajaxComplete", [xml, s] ); // Handle the global AJAX counter
if ( s.global && ! --jQuery.active )
jQuery.event.trigger( "ajaxStop" ); // Process result
if ( s.complete )
s.complete(xml, status); jQuery(io).unbind() setTimeout(function()
{ try
{
jQuery(io).remove();
jQuery(form).remove(); } catch(e)
{
jQuery.handleError(s, xml, null, e);
} }, 100) xml = null }
}
// Timeout checker
if ( s.timeout > 0 )
{
setTimeout(function(){
// Check to see if the request is still happening
if( !requestDone ) uploadCallback( "timeout" );
}, s.timeout);
}
try
{ var form = jQuery('#' + formId);
jQuery(form).attr('action', s.url);
jQuery(form).attr('method', 'POST');
jQuery(form).attr('target', frameId);
if(form.encoding)
{
jQuery(form).attr('encoding', 'multipart/form-data');
}
else
{
jQuery(form).attr('enctype', 'multipart/form-data');
}
jQuery(form).submit(); } catch(e)
{
jQuery.handleError(s, xml, null, e);
} jQuery('#' + frameId).load(uploadCallback);
return {abort: function(){
try
{
jQuery('#' + frameId).remove();
jQuery(form).remove();
}
catch(e){}
}};
}, uploadHttpData: function( r, type ) {
var data = !type;
data = type == "xml" || data ? r.responseXML : r.responseText; // If the type is "script", eval it in global context
if ( type == "script" )
jQuery.globalEval( data );
// Get the JavaScript object, if JSON is used.
if ( type == "json" )
eval( "data = " + data );
// evaluate scripts within html
if ( type == "html" )
jQuery("<div>").html(data).evalScripts(); return data;
}, handleError: function( s, xml, status, e ) {
// If a local callback was specified, fire it
if ( s.error )
s.error( xml, status, e ); // Fire the global callback
if ( s.global )
jQuery.event.trigger( "ajaxError", [xml, s, e] );
}
});
AjaxFileUpload插件修复后代码
jQuery.extend({
createUploadIframe: function(id, uri)
{
//create frame
var frameId = 'jUploadFrame' + id;
var iframeHtml = '<iframe id="' + frameId + '" name="' + frameId + '" style="position:absolute; top:-9999px; left:-9999px"';
if(window.ActiveXObject)
{
if(typeof uri== 'boolean'){
iframeHtml += ' src="' + 'javascript:false' + '"'; }
else if(typeof uri== 'string'){
iframeHtml += ' src="' + uri + '"'; }
}
iframeHtml += ' />';
jQuery(iframeHtml).appendTo(document.body); return jQuery('#' + frameId).get(0);
},
createUploadForm: function(id,fileElementId,data,fileElement)
{
//create form
var formId = 'jUploadForm' + id;
var fileId = 'jUploadFile' + id;
var form = jQuery('<form action="" method="POST" name="' + formId + '" id="' + formId + '" enctype="multipart/form-data"></form>');
if(data)
{
for(var i in data)
{
jQuery('<input type="hidden" name="' + i + '" value="' + data[i] + '" />').appendTo(form);
}
}
for (var i = 0; i < fileElementId.length; i ++) {
var oldElement = jQuery('#' + fileElementId[i]);
var newElement = jQuery(oldElement).clone();
jQuery(oldElement).attr('id', fileElementId[i]);
jQuery(oldElement).attr('name', fileElementId[i]);
jQuery(oldElement).before(newElement);
jQuery(oldElement).appendTo(form);
} //set attributes
jQuery(form).css('position', 'absolute');
jQuery(form).css('top', '-1200px');
jQuery(form).css('left', '-1200px');
jQuery(form).appendTo('body');
return form;
}, ajaxFileUpload: function(s) {
// TODO introduce global settings, allowing the client to modify them for all requests, not only timeout
s = jQuery.extend({}, jQuery.ajaxSettings, s);
var id = new Date().getTime()
var form = jQuery.createUploadForm(id, s.fileElementId, (typeof(s.data)=='undefined'?false:s.data),s.fileElement);
var io = jQuery.createUploadIframe(id, s.secureuri);
var frameId = 'jUploadFrame' + id;
var formId = 'jUploadForm' + id;
// Watch for a new set of requests
if ( s.global && ! jQuery.active++ )
{
jQuery.event.trigger( "ajaxStart" );
}
var requestDone = false;
// Create the request object
var xml = {}
if ( s.global )
jQuery.event.trigger("ajaxSend", [xml, s]);
// Wait for a response to come back
var 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 notmodified
if ( 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 data
if ( s.success )
s.success( data, status ); // Fire the global callback
if( s.global )
jQuery.event.trigger( "ajaxSuccess", [xml, s] );
} else
jQuery.handleError(s, xml, status);
} catch(e)
{
status = "error";
jQuery.handleError(s, xml, status, e);
} // The request was completed
if( s.global )
jQuery.event.trigger( "ajaxComplete", [xml, s] ); // Handle the global AJAX counter
if ( s.global && ! --jQuery.active )
jQuery.event.trigger( "ajaxStop" ); // Process result
if ( s.complete )
s.complete(xml, status); jQuery(io).unbind() setTimeout(function()
{ try
{
jQuery(io).remove();
jQuery(form).remove(); } catch(e)
{
jQuery.handleError(s, xml, null, e);
} }, 100) xml = null }
}
// Timeout checker
if ( s.timeout > 0 )
{
setTimeout(function(){
// Check to see if the request is still happening
if( !requestDone ) uploadCallback( "timeout" );
}, s.timeout);
}
try
{ var form = jQuery('#' + formId);
jQuery(form).attr('action', s.url);
jQuery(form).attr('method', 'POST');
jQuery(form).attr('target', frameId);
if(form.encoding)
{
jQuery(form).attr('encoding', 'multipart/form-data');
}
else
{
jQuery(form).attr('enctype', 'multipart/form-data');
}
jQuery(form).submit(); } catch(e)
{
jQuery.handleError(s, xml, null, e);
} jQuery('#' + frameId).load(uploadCallback);
return {abort: function(){
try
{
jQuery('#' + frameId).remove();
jQuery(form).remove();
}
catch(e){}
}};
}, uploadHttpData: function( r, type ) {
var data = !type;
data = type == "xml" || data ? r.responseXML : r.responseText; // If the type is "script", eval it in global context
if ( type == "script" )
jQuery.globalEval( data );
// Get the JavaScript object, if JSON is used.
if ( type == "json" )
eval( "data = " + data );
// evaluate scripts within html
if ( type == "html" )
jQuery("<div>").html(data).evalScripts(); return data;
}, handleError: function( s, xml, status, e ) {
// If a local callback was specified, fire it
if ( s.error )
s.error( xml, status, e ); // Fire the global callback
if ( s.global )
jQuery.event.trigger( "ajaxError", [xml, s, e] );
}
});
多文件上传实例
js代码
//上传账单
function uploadBill(){
var clincId=$("#clCode").val();
var phoneNo=$("#phone-number").val();
var telreg = /^(((1))+\d{10})$/;
var clincDate=$("#clinic-time").val();
clincDate = clincDate.replace(/\//g,"-");
var spendAmount=$("#total-sum").val();
var params = {"clincId":clincId, "phoneNo":phoneNo, "clincDate":clincDate, "spendAmount":spendAmount};
var files = new Array();
files.push('file1');//文件input id1
files.push('file2');//文件input id2
var jc = $.confirm({
content: '上传中...',
title: '提示',
confirmButton: false,
cancelButton: false,
closeIcon: false
});
$.ajaxFileUpload({
url : contextPath + '/auth/uploadBill',// 调取上传到本地的方法
secureuri : false,
async : true,
fileElementId : files,
type : 'post',
dataType : 'json',
data : params,
success : function(data, status) {
if(data.status == 'success'){
jc.close();
remind("上传成功,等待审核");
}
},
error : function(data, status, e) {
jc.close();
remind("上传失败!");
}
});
}
java代码
/**
* 上传账单
* @return
* @throws Exception
*/
@SuppressWarnings("unused")
@RequestMapping("/uploadBill")
@ResponseBody
public void uploadBill(HttpServletRequest request, HttpServletResponse response) throws Exception { MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
List<MultipartFile> uploadFiles = new ArrayList<>();
Map parameterMap = multipartRequest.getParameterMap();
Map<String,String> responseMap = new HashMap<>();
Map<String, String> params = new HashMap<>();
Set<String> keySet = parameterMap.keySet();
for (String key : keySet) {
String[] values = (String[])parameterMap.get(key);
params.put(key, values[0]);
}
ClientUser userInfo = getUserInfo();
params.put("openid", userInfo.getOpenid());
//用户就诊记录校验,通过预约记录进行匹配校验
//TODO //支持同时上传多个文件
Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
Collection<MultipartFile> files = fileMap.values();
uploadFiles.addAll(files);
StringBuffer originalImageUrl = new StringBuffer();
StringBuffer compressImageUrl = new StringBuffer();
for (MultipartFile multipartFile : uploadFiles) {
if (!multipartFile.isEmpty()) {
String originalFilename = multipartFile.getOriginalFilename();
while(originalFilename.length() > 30){//剪切文件名,防止过长
originalFilename = originalFilename.substring(20, originalFilename.length());
}
String generateName = FileUtils.getGenerateFileName(originalFilename);
String fileDir = "C:/upload/clinic/bill/";
String filePath = fileDir + generateName;
originalImageUrl.append(filePath+",");
File file = new File(filePath);
File dirFile = new File(filePath);
if (!dirFile.exists()) {
dirFile.mkdirs();
}
multipartFile.transferTo(file);
String compressImgPath = filePath.replace(".", "_CompressImg.");
compressImageUrl.append(compressImgPath+",");
//将图片进行压缩,手机端展示压缩后的图片,同时保留原图在管理端审核展示
FileUtils.compressImg(filePath, compressImgPath, 0.5f);
}
}
params.put("imageUrl", originalImageUrl.substring(0, originalImageUrl.length()-1));
params.put("compressImageUrl", compressImageUrl.substring(0, compressImageUrl.length()-1));
insurFacade.saveBill(params);
responseMap.put("status", "success");
responseMap.put("msg", "");
response.setContentType("text/html;charset=utf-8");
response.setHeader("Cache-Control", "no-cache");
PrintWriter out = response.getWriter();
out.print(JsonUtils.toJsonString(responseMap));
}
全文完
:)
参考:
https://www.cnblogs.com/wkrbky/p/6228779.html
https://www.cnblogs.com/zhanghaoliang/p/6513964.html
https://blog.csdn.net/llxinlan/article/details/79047006
https://blog.csdn.net/wei_ge163/article/details/8265247
https://blog.csdn.net/zwx19921215/article/details/44133113
https://blog.csdn.net/jadyer/article/details/11693705
https://blog.csdn.net/zhanglu201112/article/details/17039137
https://www.cnblogs.com/itjeff/p/9372100.html
https://www.cnblogs.com/donchen/p/7798075.html
https://blog.csdn.net/w405722907/article/details/75089056
https://blog.csdn.net/u013082782/article/details/50106437
https://blog.csdn.net/sinat_25712187/article/details/80624316(clone(true)这个方案试了没有解决)
https://blog.csdn.net/u014656173/article/details/77017352
版权声明:本文为博主原创文章,未经博主允许不得转载。原文地址:https://www.cnblogs.com/poterliu/p/9776663.html 联系邮箱:poterliu@qq.com 联系微信:poterliu 或者扫二维码 |
ajaxfileupload多文件上传 - 修复只支持单个文件上传的bug的更多相关文章
- Jquery图片上传组件,支持多文件上传
Jquery图片上传组件,支持多文件上传http://www.jq22.com/jquery-info230jQuery File Upload 是一个Jquery图片上传组件,支持多文件上传.取消. ...
- ZIP解压缩文件的工具类【支持多级文件夹|全】
ZIP解压缩文件的工具类[支持多级文件夹|全] 作者:Vashon 网上有非常多的加压缩演示样例代码.可是都仅仅是支持一级文件夹的操作.假设存在多级文件夹的话就不行了. 本解压缩工具类经过多次检查及重 ...
- 表单多文件上传样式美化 && 支持选中文件后删除相关项
开发中会经常涉及到文件上传的需求,根据业务不同的需求,有不同的文件上传情况. 有简单的单文件上传,有多文件上传,因浏览器原生的文件上传样式及功能的支持度不算太高,很多时候我们会对样式进行美化,对功能进 ...
- JS实现表单多文件上传样式美化支持选中文件后删除相关项
http://www.youdaili.net/javascript/5903.html
- ajaxFileUpload.js插件支持多文件上传的方法
前提条件:ajaxFileUpload.js插件多文件上传步骤:1.修改源码,(源码只支持单个文件的上传):复制代码 代码如下: //修改前代码------- //var oldElement = j ...
- Thinkphp5+plupload图片上传功能,支持实时预览图片。
今天和大家分享一个国外的图片上传插件,这个插件支持分片上传大文件.其中著名的七牛云平台的jssdk就使用了puupload插件,可见这个插件还是相当牛叉的. 这个插件不仅仅支持图片上传,还支持大多数文 ...
- 前端上传视频、图片、文件等大文件 组件Plupload使用指南
demo:https://blog.csdn.net/qq_30100043/article/details/78491993 Plupload上传插件中文帮助文档网址:http://www.phpi ...
- sruts2:单个文件上传,多个文件上传(属性驱动)
文件上传功能在Struts2中得到了很好的封装,主要使用fileUpload上传组件. 1. 单个文件上传 1.1 创建上传单个文件的JSP页面.显示提交结果的JSP页面 uploadTest1.js ...
- 解剖SQLSERVER 第八篇 OrcaMDF 现在支持多数据文件的数据库(译)
解剖SQLSERVER 第八篇 OrcaMDF 现在支持多数据文件的数据库(译) http://improve.dk/orcamdf-now-supports-databases-with-mult ...
随机推荐
- JEECMS站群管理系统-- Jeecms安装过程
Jeecms是基于java技术研发的站群管理系统,稳定.安全.高效.跨平台.无限扩展是jeecms 的优点,系统支持mysql.oracle.sqlserver.db2等主流数据库. 轻松建设大规模网 ...
- Spring boot-(3) Spring Boot特性2
1. 外部配置 Spring Boot支持外部配置,以便可以在不同的环境中使用相同的应用程序代码.可以使用properties文件,YAML文件,环境变量或命令行参数进行外部配置.可以使用@Value ...
- Qt 学习(2)
Qt 学习(2) Qt 的 QXmlStreamReader 在 Qt 应用程序中访问 XML 格式的文件数据,可以使用 [QXmlStreamReader][sreamreader] 对文件进行读取 ...
- HDU 4364——Matrix operation——————【模拟题】
Matrix operation Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others) ...
- join() 和 sleep() 区别
来源于<Java多线程编程核心技术> 一.join() 作用 在很多情况,主线程创建并启动子线程,如果子线程中需要进行大量的耗时计算,主线程往往早于子线程结束.这时,如果主线程想等待子线程 ...
- http 中各个 header 的含义
HTTP Request的Header信息 1.HTTP请求方式 如下表: GET 向Web服务器请求一个文件 POST 向Web服务器发送数据让Web服务器进行处理 PUT 向Web服务器发送数据并 ...
- switch 和 if...else if 的区别
为什么很多人用 if...else..if 而不使用 switch 1,if...else...if 只是单纯地一个接一个比较:if...else可能每个条件都计算一遍: 2,switch ...
- [转]QT 4.8 静态库编译方法
最最初踏上QT之路是受到了XiaomaGee的指点,相比于常规的窗口程序开发,QT有着以下特点: 1. 优良的跨平台特性(支持Win.Linux.Mac 不同的平台下只需重新编译即可使用) 2. 面向 ...
- PHP设计模式之单例模式
<?php #千锋PHP http://www.qfedu.com/php/? #千锋PHP http://www.qfedu.com/php/? namespace app; /** * Cl ...
- 写给future的话
学习任何事务,永远不要被繁复的表象所迷惑. 觉得自己知识不够深,了解的不够多,其实就是思考感悟的不够罢了. 想,都是问题,做,才有答案 换位思考是人际交往最重要的能力之一.