Upload files with springMVC and AjaxForm

  • 2021-07-02 23:22:12
  • OfStack

Recently in the project need to upload files, before 1 straight are form submitted, tried 1 under AjaxForm, feeling better to use, write an essay under mark, for later use.
Preparations:
Download jquery-form. js

Related jar:

commons-fileupload-1.1.1.jar

commons-io-1.3.2.jar

Configure multipartResolver at spring-servlet. xml:


<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> 

This is a must, otherwise it won't work well.
Pages:


 <!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%" > Select a file: </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=" Determine " type="submit" />
  <span style="display:inline-block;width:25px;"></span>
  <a class="nui-button" iconCls="icon-cancel" style="width:60px;" onclick="cancel"> Cancel </a>
 </div> 
 </form>   
</div>
</body>
</html> 

Core js:


 var msg;
$(function(){
nui.parse();
//ajax Configure 
var options = { 
  url: contextPath+"/webapp/cfProjectType/importExcel",
  beforeSubmit: showRequest, // Pre-submission processing  
  success:  showResponse, // Processing complete  
  resetForm: true, 
  dataType: 'json' 
  }; 
 $('#fileUpload').submit(function() { // Attention 
  $(this).ajaxSubmit(options); 
  return false;// Prevent dialog  Automatic shutdown 
  });
})

// Execute successful callback function 
function showResponse(e) {
 nui.hideMessageBox(msg);
 if (e.importFlag == true) {
  CloseWindow("ok");
 } else {
  // To the wrong 1 Some treatment 
 }
}

// Pre-submission 1 Some calibration 
function showRequest(formData, jqForm, options){
 if(formData[0].value=="" || formData[0].value==null){
  nui.alert(" Please select a file ");
  return false;
 }
 var fileName = $("#uploadFile").val().split("\\").pop();
 var strs = new Array(); // Definition 1 Array 
 strs = fileName.split('.');
 var suffix = strs [strs .length - 1];
 if (suffix != 'xls' && suffix != 'xlsx') {
  nui.alert(" Please select excel Files! ");
  return false;
 }
 msg = nui.loading("Loading", "Please waiting");
} 

java code:


 @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);
    // Determine whether the save directory of the uploaded file exists 
    if (!fileIn.exists() && !fileIn.isDirectory()) {
     // Create Directory 
     fileIn.mkdirs( Path );
    }
    // Copy uploaded files to folder 
    myfile.transferTo(new File( Path + Filename ));
   }
   }
  } 

Another method I used earlier here, FileUtils. copyInputStreamToFile (InputStream arg0, File arg1), can also save files below the path

For more exciting content, please refer to the topics "ajax Upload Technology Summary", "javascript File Upload Operation Summary" and "jQuery Upload Operation Summary" for learning.


Related articles: