SpringMVC结合AjaxForm实现文件上传详解

作者:键盘侠

时间:2026-10-30

浏览:105

本文介绍如何在SpringMVC项目中利用jquery-form.js插件实现Ajax文件上传。详细说明了所需的commons-fileupload和commons-io依赖,Spring配置multipartResolver的关键参数,以及前端jQuery提交与后端MultipartFile接收的完整代码示例。

文章目录

SpringMVC AjaxForm文件上传实现

近期在项目开发中涉及文件上传功能,以往多采用传统Form表单提交方式。经过尝试,发现使用AjaxForm插件效果更佳。在此记录相关实现过程,便于后续查阅与复用。

实现该功能需引入以下相关JAR包:

commons-fileupload-1.1.1.jar

commons-io-1.3.2.jar

接下来需在spring-servlet.xml文件中配置multipartResolver,具体配置如下:


<bean id="multipartResolver"
 class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
 <property name="defaultEncoding" value="utf-8" />
 <property name="maxUploadSize" value="10485760000" />
 <property name="maxInMemorySize" value="40960" />
</bean> 

此配置步骤不可或缺,若缺失可能导致上传功能无法正常运行。


 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8" session="false" %>
<html>
<!-- 
- Author(s): xieshuang
- Date: 2016-06-20 13:46:20
- Description:
-->
<head>
<title>Title</title>
<meta http-equiv="content-type" content="text/html; charset=UTF-8"/>
<script src="<%=request.getContextPath()%>/common/nui/nui.js" type="text/javascript"></script>
<script src="<%=request.getContextPath()%>/common/nui/jquery/jquery-form.js" type="text/javascript"></script>
<script type="text/javascript" src="<%=request.getContextPath()%>/page4nui/master/projecttype/js/projecttype_import.js"></script>
<script type="text/javascript">
 var contextPath="<%=request.getContextPath()%>";
</script>
</head>
<body>
<div id="test" class="nui-fit" style="padding-top:5px;min-width:300px;min-height:180px;">
 <form id="fileUpload" method="post" enctype="multipart/form-data">
 <div id="dataImport" style="width:100%;overflow:hidden;">
  <table style="width:100%;table-layout:fixed;" class="nui-form-table" >
   <tr>
    <th align="right" style="width:25%" >选择文件:</th>
    <td>
     <input id="uploadFile" type="file" name="file" style="width:90%;"><font style="color:red;width:5%;"> *</font>
    </td>
   </tr>
  </table>  
 </div>
 
 <div style="width:100%;padding-top:10px;" align="center">
  <input style="width:60px;" iconCls="icon-ok" value="确定" type="submit" />
  <span style="display:inline-block;width:25px;"></span>
  <a class="nui-button" iconCls="icon-cancel" style="width:60px;" onclick="cancel">取消</a>
 </div> 
 </form>   
</div>
</body>
</html> 

前端页面HTML结构如下:


 var msg;
$(function(){
nui.parse();
//ajax配置
var options = { 
  url: contextPath+"/webapp/cfProjectType/importExcel",
  beforeSubmit: showRequest, //提交前处理 
  success:  showResponse, //处理完成 
  resetForm: true, 
  dataType: 'json' 
  }; 
 $('#fileUpload').submit(function() { //注意
  $(this).ajaxSubmit(options); 
  return false;//防止dialog 自动关闭
  });
})

//执行成功回调函数
function showResponse(e) {
 nui.hideMessageBox(msg);
 if (e.importFlag == true) {
  CloseWindow("ok");
 } else {
  //对错误的一些处理
 }
}

//提交前的一些校验
function showRequest(formData, jqForm, options){
 if(formData[0].value=="" || formData[0].value==null){
  nui.alert("请选择文件");
  return false;
 }
 var fileName = $("#uploadFile").val().split("\\").pop();
 var strs = new Array(); //定义一数组
 strs = fileName.split('.');
 var suffix = strs [strs .length - 1];
 if (suffix != 'xls' && suffix != 'xlsx') {
  nui.alert("请选择excel文件!");
  return false;
 }
 msg = nui.loading("Loading", "Please waiting");
} 

核心JavaScript代码实现如下:


 @SuppressWarnings("unchecked")
@RequestMapping("/webapp/cfProjectType/importExcel")
@ResponseBody
public Map<String, Object> importExcel(@RequestParam("file") MultipartFile[] files, HttpServletRequest request)
  throws Throwable {
 //long starttiem = System.currentTimeMillis();
 InputStream fis;
 fis = null;
 File fileIn = null;
 try {
  for (MultipartFile myfile : files) {
   if (!myfile.isEmpty()) {
    String realPath = request.getSession().getServletContext().getRealPath("/export");
    fileIn = new File(realPath);
    //判断上传文件的保存目录是否存在
    if (!fileIn.exists() && !fileIn.isDirectory()) {
     //创建目录
     fileIn.mkdirs(路径);
    }
    //将上传的文件复制到文件夹下
    myfile.transferTo(new File(路径+文件名));
   }
   }
  } 

在Java后端处理中,此前曾使用FileUtils.copyInputStreamToFile(InputStream arg0, File arg1)方法,同样可将文件保存至指定路径。

如需了解更多相关内容,建议参考专题《ajax上传技术汇总》、《javascript文件上传操作汇总》及《jQuery上传操作汇总》进行深入学习。

以上内容为本文全部介绍,希望能为读者的学习提供有益帮助,同时也欢迎大家继续支持本站。

实用工具推荐

电子包浆

绿化、压缩、噪点和虚拟水印,自由调节做旧程度。

使用 ›
图片压缩

选择画质和输出格式,预览压缩前后的大小。

使用 ›
相关文章