Tip: after the article is written, the directory can be generated automatically. Please refer to the help document on the right for how to generate it
1, About multipart requests
The data submitted by the forms we generally use are text data, such as our user information form. When the form is submitted, the "attribute value" in the form will be spelled into a string and submitted:
"name="+ uname +"&sex="+ sex +"&phoneNum="+uphone
This method is very simple for submitting text data, but not for binary files such as pictures and videos. So how to submit documents?
Here we use a thing called multipart form. Multipart form is different from the ordinary form introduced above. It divides the form into blocks. Each field in the form corresponds to a block, and each block has its own data type.
2, Configure multipart resolver
To upload a file is actually to parse a music request. DispatchServlet is not responsible for resolving the music request itself, but delegates a class that implements the MultipartResolver interface to resolve the music request. After Spring 3.1, Spring provides two ready-made implementation classes of MultipartResolver interface:
- **Common mutipart resolver: * * parse the music request by using Jakarta Commons FileUpload
- **Standardservlet mutipart resolver: * * relies on Servlet3.0 to resolve music requests
To realize the file upload function, we only need to configure either of the two bean s in the project.
Method 1: parse the music request through the standardservlet music resolver:
1. Configure the bean of multipartResolver in the xml file
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" id="viewResolver"> <property name="prefix" value="/WEB-INF/views/"/> <property name="suffix" value=".jsp"/> </bean> <bean id="multipartResolver" class="org.springframework.web.multipart.support.StandardServletMultipartResolver"/>
2. Configure musipartresolver related properties in the web.xml file
<servlet> <servlet-name>DispatcherServlet</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:springmvc.xml</param-value> </init-param> <load-on-startup>1</load-on-startup> <multipart-config> <location>G:\input</location> </multipart-config> </servlet>
There are three configuration items in music config. I have configured one in the figure below:
- location: the temporary folder used to upload files. It is an absolute path. Note that this attribute is required
- Max file size: the maximum value of uploaded files, in byte s. There is no limit by default
- Max request size: the maximum value of the entire music request. The unit is byte. There is no limit by default
Method 2: parse the music request through the commonmusic resolver
1. This configuration method needs to add a third-party class library, and the configuration depends on
<dependency> <groupId>commons-fileupload</groupId> <artifactId>commons-fileupload</artifactId> <version>1.3.1</version> </dependency>
2. Similarly, configure the bean of multipartResolver in the xml file
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" id="viewResolver"> <property name="prefix" value="/WEB-INF/views/"/> <property name="suffix" value=".jsp"/> </bean> <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> <property name="maxUploadSize" value="100000" /> <property name="maxInMemorySize" value="100000" /> </bean>
In this way, there is no need to configure the multipartconfiglelement element in the web.xml file, and the location attribute of the uploaded file is optional.
It should be noted that when configuring bean s in these two methods, the id is multipartResolver. Why? We can take a look at the source code in DispatchServlet. There is such a method:
private void initMultipartResolver(ApplicationContext context) { try { this.multipartResolver = (MultipartResolver)context.getBean("multipartResolver", MultipartResolver.class); if(this.logger.isDebugEnabled()) { this.logger.debug("Using MultipartResolver [" + this.multipartResolver + "]"); } } catch (NoSuchBeanDefinitionException var3) { this.multipartResolver = null; if(this.logger.isDebugEnabled()) { this.logger.debug("Unable to locate MultipartResolver with name \'multipartResolver\': no multipart request handling provided"); } } }
This method will get the bean with id multipartResolver from the Spring context as its MutipartResolver by default.
3, Controller
After configuring in any of the above ways, Spring is ready to accept the music part request. Next, you need to write a controller to receive the uploaded files:
@Controller public class FileController { @RequestMapping(value = "/fileUpload",method = RequestMethod.POST) @ResponseBody public String uploadFile(@RequestParam("file") MultipartFile file){ if (file.isEmpty()){ return "Upload failed!"; } else { //Location of documents String rootPath = "G:\\output"; File dir = new File(rootPath + File.separator + "tmpFiles"); if (!dir.exists()) { dir.mkdirs(); } //Write file to server File serverFile = new File(dir.getAbsolutePath() + File.separator + file.getOriginalFilename()); try { file.transferTo(serverFile); } catch (IOException e) { return "Upload failed!"; } return "Upload succeeded"; } } }
We can see that a parameter file in this method is of type MutipartFile, that is, Spring will automatically convert the binary file in the mutipart request into an object of type MutipartFile.
4, Write a jsp test
Page code
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>Title</title> </head> <body> <form method="POST" action="fileUpload" enctype="multipart/form-data"> Upload file: <input type="file" name="file"> <input type="submit" value="Upload"> Click upload </form> </body> </html>
One thing to note here is the enctype attribute of the form. The attribute value is multipart / form data, which will tell the browser that we submitted a music request instead of an ordinary form request.