The file upload of Spring MVC framework is based on the Commons fileUpload component, which is further encapsulated, which simplifies the code implementation of file upload and eliminates the programming differences of different upload components.
MultipartResolver interface
It is very easy to upload files in Spring MVC. It provides direct support for file upload, that is, MultpartiResolver interface. MultipartResolver is used to process the upload request and package the upload request into the data that can directly obtain the file, so as to facilitate operation.
The MultpartiResolver interface has the following two implementation classes:
- Standard servlet multipartresolver: uses the upload method of Servlet 3.0 standard.
- Commons multipartresolver: common file upload of Apache is used to complete the specific upload operation.
The MultpartiResolver interface has the following methods.
name | effect |
---|---|
byte[] getBytes() | Returns the contents of the file as a byte array |
String getContentType() | Returns the content type of the file |
InputStream getInputStream() | Returns an InputStream from which to read the contents of the file |
String getName() | Returns the name of the request parameter |
String getOriginalFillename() | Returns the name of the original file submitted by the client |
long getSize() | Returns the size of the file in bytes |
boolean isEmpty() | Judge whether the uploaded file is empty |
void transferTo(File destination) | Save the uploaded file to the target directory |
Next, we use common multipartresolver to complete file upload, which is divided into two parts: single file upload and multi file upload.
Single file upload
1. Import jar file
The file upload uses the Apache Commons FileUpload component, which needs to be imported into commons-io-2.4 Jar and commons-fileupload-1.2.2 Jar two jar files (available for download on the Apache official website).
2. Configure MultipartResolver
Use commonsmultipartresolver to configure the MultipartResolver parser in springmvc servlet Add the following XML code
<!-- to configure MultipartResolver,For uploading files, use spring of CommonsMultipartResolver --> <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> <property name="maxUploadSize" value="5000000" /> <property name="defaultEncoding" value="UTF-8" /> </bean>
- defaultEncoding: the encoding format of the request. The default is ISO-8859-1 and set here as UTF-8 (Note: defaultEncoding must be consistent with pageEncoding in JSP in order to correctly read the contents of the form).
- maxUploadSize: the maximum size of the uploaded file, in bytes.
3. Compile file upload form page
The encoding type of the form responsible for file upload must be "multipart / form data"
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html PUBLIC "-//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; charset=UTF-8"> <title>File upload</title> </head> <body> <form action="${pageContext.request.contextPath }/fileupload" method="post" enctype="multipart/form-data"> Select File:<input type="file" name="myfile"><br> Document description:<input type="text" name="description"><br> <input type="submit" value="Submit"> </form> </body> </html>
For form based file upload, you need to use the enctype attribute, set its value to multipart / form data, and set the form submission method to post.
The enctype attribute of the form specifies the encoding method of the form data. This attribute has the following three values.
- application/x-www-form-urlencoded: This is the default encoding method. It only processes the value attribute value in the form field.
- Multipart / form data: this encoding method processes form data in the form of binary stream, and encapsulates the contents of the file specified in the file field into the request parameters.
- text/plain: this encoding method can only be used when the action attribute of the form is in the form of "mailto:" URL. It is mainly applicable to sending mail directly through the form.
It can be seen from the explanation of the above three attributes that when uploading files based on forms, the attribute value of enctype should be multipart / form data.
5. Write controller
Create net biancheng. Controller package, under which a FileUploadController control class is created. The specific code is as follows.
package net.biancheng.controller; import java.io.File; import javax.servlet.http.HttpServletRequest; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.RequestMapping; import net.biancheng.po.FileDomain; @Controller public class FileUploadController { // Get an object used to record the log, so that when printing information, you can mark which kind of information is printed private static final Log logger = LogFactory.getLog(FileUploadController.class); @RequestMapping("getFileUpload") public String getFileUpload() { return "fileUpload"; } /** * Single file upload */ @RequestMapping("/fileupload") public String oneFileUpload(@ModelAttribute FileDomain fileDomain, HttpServletRequest request) { /* * The location where files are uploaded to the server is "/ uploadfiles", which refers to workspace \ metadata\. plugins\org. eclipse * .wst.server.core\tmp0\wtpwebapps, Use after publishing */ String realpath = request.getServletContext().getRealPath("uploadfiles"); String fileName = fileDomain.getMyfile().getOriginalFilename(); File targetFile = new File(realpath, fileName); if (!targetFile.exists()) { targetFile.mkdirs(); } // upload try { fileDomain.getMyfile().transferTo(targetFile); logger.info("success"); } catch (Exception e) { e.printStackTrace(); } return "showFile"; } }
Multi file upload
Based on the above code, realize Spring MVC multi file upload