Basic concepts:

Fileupload and download is basically a web project will be used in the technology, in the web learning we use the Apache fileupload component to achieve the upload, it is encapsulated in springmvc, let us use more convenient. But the bottom layer is still implemented by Apache Fileupload. Springmvc is implemented by the MultipartFile interface to upload files.

  1. First configure the related configuration in the configuration file. XML, such as the MultipartResolver in the context of SpringMVC. Such as:
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> <! -- Maximum size of the file to be uploaded, in bytes --> <property name="maxUploadSize" value="17367648787"></property> <! </property> </bean> </bean>Copy the code
  1. The introduction of springsource.org.apache.commons.fileupload and springsource.org.apache.commons.io two jars

Note: If you are using Maven for dependency management, it is in POM.xml

Related file configuration

< the dependency > < groupId > Commons fileupload - < / groupId > < artifactId > Commons fileupload - < / artifactId > < version > 1.3.2 < / version > </dependency>Copy the code
  1. On the front page, you must set POST to method for submitting the form and encType to Multipart /form-data. Only in this case will the browser send the selected file to the server as binary data

  2. SpringMVC binds the uploaded file to the MultipartFile object. MultipartFile provides methods to obtain the contents of the uploaded file, file name, and so on. Files can also be stored on hardware through the transferTo () method.

Common methods in the MultipartFile object are as follows:

Void transferTo(File dest) : save the uploaded File to a directory File; # String getOriginalFilename() : gets the original name of the uploaded file. # String getContentType[] : gets the MIME type of the file, such as image/ JPEG. # Boolean isEmpty() : gets whether the file has been uploadedCopy the code

5. Receive in the control layer, use the MultipartFile object as the parameter, receive the file sent from the front end, write the file into the local file, and upload operation is completed. Receive in the control layer, use the MultipartFile object as the parameter, receive the file sent from the front end, and write the file into the local file. The upload is complete

@RequestMapping("/upload") public String upload(@RequestParam("file") MultipartFile file, HttpServletRequest req) throws IllegalStateException, IOException {// Check whether the file is empty, If (file.isempty ()) {return "failed"; String path = req.getServletContext().getrealPath ("/WEB-INF/file"); String fileName = file.getorigInalFilename (); File filePath = new File(path, fileName); // If the file directory does not exist, create a directory if (! filePath.getParentFile().exists()) { filePath.getParentFile().mkdirs(); System.out.println(" create directory "+ filePath); } // Write to file file.transferto (filePath); return "success"; }Copy the code

Extensions (three ways to implement SpringMVC upload files)

  1. Upload files in stream mode
  2. Use the file.transfer method provided by Multipart to upload files
  3. Upload files using the methods of the classes provided by Spring MVC

For example, we have three kinds of upload files written on the front page

<%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8"%> <! PUBLIC DOCTYPE HTML "- / / / / W3C DTD HTML 4.01 Transitional / / EN" "http://www.w3.org/TR/html4/loose.dtd" > < HTML > < head > < meta  http-equiv="Content-Type" content="text/html; <title>Insert title here</title> </head> <body> <form name="serForm" action="/ fileUpload" Method ="post" enctype="multipart/form-data"> <h1> <input type="file" name="file"> <input type="submit" > Value ="upload"/> </form> <form name="Form2" action="/ project name /fileUpload2" method="post" enctype="multipart/form-data"> </h1> <input type="file" name="file"> <input type="submit" value="upload"/> <form name="Form2" action="/ project name /springUpload" method="post" encType ="multipart/form-data"> </h1> <input type="submit" value="upload"/> </form> </body> </html>Copy the code

The configuration file

<! - multipart file upload - > < bean id = "multipartResolver" class = "org.springframework.web.multipart.commons.Com monsMultipartResolver" > <property name="maxUploadSize" value="104857600" /> <property name="maxInMemorySize" value="4096" /> // Set encoding format <property name="defaultEncoding" value="UTF-8"></property> </bean>Copy the code
  1. Upload files in stream mode
@requestparam ("file") encapsulates name=file into CommonsMultipartFile object */ @RequestMapping("fileUpload",,method=RequestMethod.POST) public String fileUpload(@RequestParam("file") CommonsMultipartFile file) throws IOException {long startTime= System.currentTimemillis (); System. The out. Println (" fileName: "+ file. GetOriginalFilename ()); OS =new FileOutputStream("E:/"+new Date().gettime ()+ file.getoriginalFilename ()); InputStream is= file.getinputStream (); InputStream is= file.getinputStream (); int temp; While ((temp=is.read()))! =(-1)) { os.write(temp); } os.flush(); os.close(); is.close(); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } long endTime=System.currentTimeMillis(); System.out.println(" method 1 runtime: "+ string.valueof (endTime-startTime)+"ms"); return "/success"; }Copy the code

2. Upload files using the file.transfer method provided by Multipart

/* * Use file.transto to save the uploaded file */ @requestMapping ("fileUpload2",method= requestMethod.post) public String fileUpload2(@RequestParam("file") CommonsMultipartFile file) throws IOException { long startTime=System.currentTimeMillis(); System. The out. Println (" fileName: "+ file. GetOriginalFilename ()); String path="E:/"+new Date().getTime()+file.getOriginalFilename(); File newFile=new File(path); // Write directly to the file using the CommonsMultipartFile method (notice this time) file.transferto (newFile); long endTime=System.currentTimeMillis(); System.out.println(" method 2: "+ string.valueof (endTime-startTime)+"ms"); return "/success"; }Copy the code

3. Upload files using the methods of classes provided by Spring MVC

*/ @requestMapping ("springUpload",method= requestMethod. POST) public String springUpload(HttpServletRequest request) throws IllegalStateException, IOException { long startTime=System.currentTimeMillis(); CommonsMultipartResolver multipartResolver=new CommonsMultipartResolver( request.getSession().getServletContext()); / / check whether there is in the form enctype = "multipart/form - the data" if (multipartResolver. IsMultipart (request)) {/ / request will become part of the request MultipartHttpServletRequest multiRequest=(MultipartHttpServletRequest)request; / / get all file names in the multiRequest Iterator iter. = multiRequest getFileNames (); While (it.hasnext ()) {// iterates through all files at once. MultipartFile File =multiRequest.getFile(it.next ().toString()); if(file! =null) { String path="E:/springUpload"+file.getOriginalFilename(); TransferTo (new file (path)); // Upload file.transferto (new file (path)); } } } long endTime=System.currentTimeMillis(); System.out.println(" method 3 runtime: "+ string.valueof (endTime-startTime)+"ms"); return "/success"; }Copy the code
Test upload time:

The first time I used a 4M file:

FileName: test.rar Runtime of method 1:14712ms Runtime of method 2:5ms Runtime of method 3:4ms

The second time: I use a 50M file mode a slow progress, estimated to take 5 minutes method 2 run time: 67ms method 3 run time: 80ms

Therefore, we prefer to use the built-in file upload method in SpringMVC