1. 导入JQuery相关JS文件

<script src="<@full_path path="js/jquery.js"/>" type="text/javascript"></script>

<script src="<@full_path path="js/ajaxfileupload.js"/>" type="text/javascript"></script>

这边ajaxfileupload.js有点特殊,请使用如下改造后的原文件内容:

jQuery.extend({createUploadIframe: function(id, uri){//create framevar 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)  {  //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));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 {jQuery(io).remove();jQuery(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 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 () {}};   },uploadHttpData: function( r, type ) {alert("type is " + type);var data = !type;alert("data1 is " + data);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" ) {alert("in json,data is " + data);eval( "data = " + data );}// evaluate scripts within htmlif ( type == "html" )jQuery("<div>").html(data).evalScripts();return data;}
})

2. 相关页面调用例子。(需引入相关JS)

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>导入数据应用</title>
<#include "/views/head.html"/><script>function test() {var baseUrl = "<@full_path path="/"/>";var arrId = [];arrId[0] = "appExcel";arrId[1] = "zipFile";alert("arrId[0] is " + arrId[0] + ",arrId[1] is " + arrId[1]);$.ajaxFileUpload(  { url:baseUrl + 'app/test', //你处理上传文件的服务端secureuri:false,fileElementId:arrId,dataType: 'json',success: function (data, status){              alert("is success. status is " + status);alert("in success data is " + data.desc);},error: function (data, status, e){  alert("is error. status is " + status + ",and e is " + e);}});}function commitInput(){var zipFile = document.getElementById("zipFile");var appExcel = document.getElementById("appExcel");var zipValue=zipFile.value;var appExcelValue=appExcel.value;var zipflag=false;var appExcelflag=false;var zipCheck = document.getElementById("zip");if(appExcelValue != "" && appExcelValue != null){var format = appExcelValue.substr(appExcelValue.lastIndexOf("."));if(format==".xls" || format==".csv" || format == ".xlsx"){document.getElementById("appExcelInfo").innerHTML="";appExcelflag=true;}else{document.getElementById("appExcelInfo").innerHTML="上传的格式不对";}}if(zipCheck.checked==true){if(zipValue != "" && zipValue != null){if(zipValue.substr(zipValue.lastIndexOf("."))==".zip"){document.getElementById("zipInfo").innerHTML="";zipflag=true;}else{document.getElementById("zipInfo").innerHTML="上传的格式不对";}}if(zipflag&&appExcelflag){//$.jBox.close(true);//window.parent.closeBatchApp();setTimeout("window.parent.closeBatchApp()",100);}return zipflag&&appExcelflag;}if(appExcelflag){setTimeout("window.parent.closeBatchApp()",100);//window.parent.closeBatchApp();//return true;}//window.parent.closeBatchApp();alert(appExcelflag);return appExcelflag;}function showZip(){var zipDiv = document.getElementById("showZipInput");var zipCheck = document.getElementById("zip");var isUploadIconValue = document.getElementById("isUploadIcon");if(zipCheck.checked==true){zipDiv.style.display="block";isUploadIconValue.value="true";}else{zipDiv.style.display="none";isUploadIconValue.value="false";}}
</script>
</head><body style="font-size:12px;">
<form method="post" name="listForm" id="listForm" action="<@full_path path='app/batchImportApps'/>" enctype="multipart/form-data" οnsubmit="return commitInput();"> <#--οnclick="return commitInput();"--><div style="margin-left:10%; margin-top:20%;"><table><tr><td align="right"><b style="font-size:14px;">csv或xls的文件:</b><input type="file" id="appExcel" name="appExcel"/><span id="appExcelInfo" style="color:red"></span><input type="checkbox" id="zip" onclick = "showZip();" /><label for="zip"><b style="font-size:14px;">上传zip文件</b></label></td></tr><tr><td aling="center" ><div style="display:none;margin-left:11%;" id="showZipInput"><b style="font-size:14px;">zip文件:</b><input type="file" id="zipFile" name="zipFile"/><span id="zipInfo" style="color:red"></span></div></td></tr><tr><td colspan=2 align="center"><input type="hidden" id="isUploadIcon" name="isUploadIcon" value="false"></td></tr></table></div><div style="margin-left:33%;"><input type="submit" value="确认上传" /><input type="button" value="test" οnclick="test()"/><input type="reset" value="重置"/></div>
</form>
</body>
</html>

3。 后台相关JAVA代码

   @RequestMapping(value = "/test", method = RequestMethod.POST)public void test(MultipartHttpServletRequest multipartRequest,HttpServletResponse response,HttpServletRequest request) {System.err.println("1234");InputStream appExcelStream = null;try {for (Iterator it = multipartRequest.getFileNames(); it.hasNext();) {  String key = (String) it.next();  MultipartFile imgFile = multipartRequest.getFile(key);  if (imgFile.getOriginalFilename().length() > 0) {  String fileName = imgFile.getOriginalFilename(); System.err.println("filename is " + fileName);OutputStream out = new FileOutputStream(new File("d://" + fileName));out.write(imgFile.getBytes());out.close();}}    response.setContentType("text/html;charset=UTF-8"); PrintWriter out1 = response.getWriter();FileUploadResp res = new FileUploadResp();res.setResult(0);res.setDesc("success.");out1.write(JSONObject.fromObject(res).toString());} catch (IOException e) {log.error("in batchImportApps,inputstream is null.");}}public static class FileUploadResp {private int result;private String desc;public int getResult() {return result;}public void setResult(int result) {this.result = result;}public String getDesc() {return desc;}public void setDesc(String desc) {this.desc = desc;}}

另:请注意,以上方法在同一个域项目中才可以正常使用。如果页面是通过部署在两个项目并且分属不同域中的话,则无法正常使用AJAX实现的。

JQuery与springmvc实现多个文件上传操作相关推荐

  1. SpringMVC数据校验、文件上传

    SpringMVC数据校验.文件上传 首先在此鸣谢所有本篇博客涉及技术给予我指导的导师,朋友! 目录: 1.文件上传流程: 2.数据校验: 3.本试验遇到的报错问题及解决办法: 4.Java文件源代码 ...

  2. java实现excel文件上传_java相关:SpringMVC下实现Excel文件上传下载

    java相关:SpringMVC下实现Excel文件上传下载 发布于 2020-6-21| 复制链接 摘记: 在实际应用中,经常会遇到上传Excel或者下载Excel的情况,比如导入数据.下载统计数据 ...

  3. SpringMVC处理Json、文件上传、拦截器

    SpringMVC处理Json.文件上传.拦截器 : 处理JSON 链接 http://repo1.maven.org/maven2/com/fasterxml/jackson/core/ 步骤 编写 ...

  4. springmvc 采用MultipartResolver进行文件上传

    springmvc 采用MultipartResolver解析文件上传请求,利用MultipartFile来进行接收文件,使服务器文件接收和保存变得异常方便. public interface Mul ...

  5. SpringMVC +layui 实现多文件上传,附加进度条

    首先在进行文件上传操作的时候,你得对layui 中文件上传的一些参数先了解一下,不要网上复制粘贴,起码你要对layui 文件上传的必备参数做一些大致掌握,也是自己学习. (1) 首先你得引入layui ...

  6. python selenium 文件上传_python-selenium -- 文件上传操作

    一.文件上传操作 win32gui.FindWindow(IPClassName,IPWindowName) 自顶层窗口开始寻找匹配条件的窗口,并返回这个窗口的句柄: IPClassName:类名,在 ...

  7. Web自动化文件上传操作_Chrom

    web自动化中适用于Chrom浏览器的文件上传操作: import win32gui import win32con#谷歌浏览器,固定用法 def file_upload(path):dialog=w ...

  8. UI自动化第七讲:winspy+pywin32实现文件上传操作

    以下实例使用百度搜索框上传文件图片搜索演示文件上传 from selenium import webdriver import time from selenium.webdriver import ...

  9. 初学SpringMVC,使用MVC进行文件上传

    最近在做一个文件上传的功能,走了不少弯路,话不多说,直接上代码: 导入各种jar包,首先是applicationContext.xml配置文件中: 1 <!-- 配置文件解析器 --> 2 ...

最新文章

  1. 伸缩门遥控器c语言程序,急求求c++编程高手,求50的阶乘,要求结果是精确的整数,打印在屏幕上。...
  2. python 列表表达式 if_python中if else如何判断表达式成立?
  3. python主要运用于-python主要应用领域有哪些?看这一篇就够了
  4. 移动互联时代:儿童教育重在内容和应用
  5. 认证授权方案之授权揭秘 (上篇)
  6. mysql普通标转分区表_MySQL分区表到普通表互转
  7. 代码合并工具_分享几款比较常用的代码比较工具
  8. python windows 消息通讯_如何使用python與windows中的事件/消息掛鈎
  9. loadrunner要点总结
  10. Google Maps API 进级:GoogleMaps中显示画中画
  11. C语言中scanf和printf格式化输入输出
  12. LaTeX 旁注 边注 Marigin Note
  13. svg--矢量图和位图
  14. 关于《网上购书系统》
  15. 新概念三-Lesson1-课文笔记
  16. 学会这几点,不懂代码也能做出炫酷可视化大屏!
  17. 青龙面板运行·小米改步
  18. 浅谈作为一名软件开发,应该学什么、怎么学、怎样更好的提高自己?
  19. 计算机文件丢失系统无法启动,文件损坏或丢失windows无法启动_windows无法启动文件损坏解决方法...
  20. 【读点论文】MnasNet: Platform-Aware Neural Architecture Search for Mobile,用神经网络搜索的方式来设计网络平衡精度与速度

热门文章

  1. 用C#编写一个进程外的COM组件示例代码讲解
  2. python中的编码问题 1
  3. 公钥、私钥、数字证书的概念 (讲得很明吧,通俗易懂)
  4. Windows 平台下Myeclipse 10 中SVN 插件使用教程(TortoiseSVN)
  5. 初等数论中的欧拉公式
  6. 微博ID:SuHua_MF
  7. JRuby 1.6.0发布
  8. 快速上手Spring WebFlux框架
  9. J2EE远程调试,远程debug你的线上Springboot项目
  10. Atitit 软件架构方法的进化与演进cs bs soa roa  msa  attilax总结