Spring’s multipart (file upload) support:-
Springs have built-in multipart support handles file uploads in web
applications. You enable this multipart support with pluggable
MultipartResolver objects, defined in the
org.springframework.web.multipart package. Spring provides one
MultipartResolver implementation for use with Commons FileUpload and
another for use with Servlet 3.0 multipart request parsing.
By default, Spring does no multipart handling, because some developers
want to handle multiparts themselves. You enable Spring multipart handling by
adding a multipart resolver to the web application’s context. Each request is
inspected to see if it contains a multipart. If no multipart is found, the
request continues as expected. If a multipart is found in the request, the
MultipartResolver that has been declared in your context is used. After
that, the multipart attribute in your request is treated like any other
attribute.
Using a MultipartResolver with Commons FileUpload:
The following example shows how to use the CommonsMultipartResolver-
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<!-- one of the properties available; the maximum file size in bytes -->
<property name="maxUploadSize" value="100000"/>
</bean>
A file upload in a form:
First, we create a form with a file input that will allow the user to upload a
form. The encoding attribute ( enctype="multipart/form-data") lets the
browser know how to encode the form as multipart request:
<html>
<head>
<title>Upload a file please</title>
</head>
<body>
<h1>Please upload a file</h1>
<form method="post" action="/form" enctype="multipart/form-data">
<input type="text" name="name"/>
<input type="file" name="file"/>
<input type="submit"/>
</form>
</body>
</html>
The next step is to create a controller that handles the file upload.we use MultipartHttpServletRequest or MultipartFile in the method parameters:
@Controller
public class FileUploadController {
@RequestMapping(value = "/form", method = RequestMethod.POST)
public String handleFormUpload(@RequestParam("name") String name,
@RequestParam("file") MultipartFile file) {
if (!file.isEmpty()) {
byte[] bytes = file.getBytes();
// store the bytes somewhere
return "redirect:uploadSuccess";
}
return "redirect:uploadFailure";
} }
The @RequestParam method parameters map to the input elements declared in the form. In this example you can save it in a database, store it on the file system.
@Controller
public class FileUploadController {
@RequestMapping(value = "/form", method = RequestMethod.POST)
public String handleFormUpload(@RequestParam("name") String name,
@RequestParam("file") Part file) {
InputStream inputStream = file.getInputStream();
// store bytes from uploaded file somewhere
return "redirect:uploadSuccess";
} }