Handling Multipart Requests in springMVC#
When handling forms, it is possible to receive a file.
Configuring the Multipart Resolver#
The resolver is a subclass of MultipartResolver, and usually using standardServletMultipartResolver is sufficient.
Simply add the following to the spring configuration file:
<bean class="org.springframework.web.multipart.support.StandardServletMultipartResolver"></bean>
or
@Bean
public MultiPartResolver getMultipartResoler(){
return new StandardServletMultipartResolver();
}
Configuring Upload Requirements#
#web.xml
<servlet>
<servlet-name>dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
<multipart-config>
<location>D:\</location>
<max-file-size>209152</max-file-size>
<max-request-size>4194304</max-request-size>
</multipart-config>
</servlet>
This configuration is done inside the DispartcherServlet using the multipart-config tag.
Make sure the location is appropriate, otherwise an error will occur due to an invalid path after uploading the file.
Controller#
@RequestMapping(value = "/upload",method = RequestMethod.POST)
@ResponseBody
public String vallidateRegisterForm(@RequestPart("myfile")MultipartFile file) throws IOException {
file.transferTo(new File(file.getOriginalFilename()));
return "upload success.";
}
We are using @RequestPart("myfile")MultipartFile file
, where MultipartFile can conveniently handle the uploaded file.
This is its interface definition:
public interface MultipartFile extends InputStreamSource {
String getName();
String getOriginalFilename();
String getContentType();
boolean isEmpty();
long getSize();
byte[] getBytes() throws IOException;
InputStream getInputStream() throws IOException;
void transferTo(File var1) throws IOException, IllegalStateException;
}
Testing the form#
<form class="fileform" action="/upload" method="post" enctype="multipart/form-data">
<input type="file" name="myfile" value="">
<input type="submit" name="" value="submit">
</form>