Heres a code sample that uploads images from a form. Please modify the action and attributes according to your need.
<form:form modelAttribute="modelClass" action="save" method="POST" enctype="multipart/form-data">
<div class="form-group">
<form:input type="file" path="productLandscapeImage" class="form-control" name="productLandscapeImage" title="Image" value=""/>
<form:errors path="productLandscapeImage" cssClass="error-tip" element="div" />
</div>
</form:form>
The model modelClass
must contain the attribute
private MultipartFile productLandscapeImage;
In your controller Class
@RequestMapping(value = { "form/save" }, method = RequestMethod.POST)
public String saveProduct(@Valid @ModelAttribute("modelClass") ModelClass modelClass
BindingResult bindingResult, Model model, HttpServletRequest httpServletRequest) {
uploadImages(modelClass, httpServletRequest);
}
private void uploadImages(ModelClass modelClass, HttpServletRequest httpServletRequest) {
if (modelClass.getProductLandscapeImage() != null
&& !modelClass.getProductLandscapeImage().getOriginalFilename().isEmpty()) {
String realPath = httpServletRequest.getSession().getServletContext().getRealPath("/resources/images/categories/");
if (!new File(realPath).exists()) {
new File(realPath).mkdirs();
}
try {
modelClass.getProductLandscapeImage().transferTo(new File(realPath + ".jpg"));
} catch (IllegalStateException | IOException e) {
// log error
}
}
}
In Your DispatcherServletInitializer Class add the following method
public class DispatcherServletInitializer extends AbstractAnnotationConfigDispatcherServletInitializer{
/**
* maxFileSize: Maximum Size of the file to be uploaded
* maxRequestSize: Maximum Size of the multipart/form-data request
* fileSizeThreshold: Size threshold after which the file will be written to disk
*
* The Size are in bytes
* 1024 * 1024 * 1 = 1MB
* 1024 * 1024 * 2 = 2MB
* 1024 * 1024 * 4 = 4MB
*/
@Override
protected void customizeRegistration(Dynamic registration) {
MultipartConfigElement multipartConfigElement = new MultipartConfigElement("/", 2097152, 8388608, 1048576);
registration.setMultipartConfig(multipartConfigElement);
}
}
In Your Web Config Class add the following bean
@Configuration
@ComponentScan(basePackages = {"com.package"})
@EnableWebMvc
public class SpringWebConfiguration implements WebMvcConfigurer{
@Bean
public MultipartResolver multipartResolver() {
return new StandardServletMultipartResolver();
}
}
Please see this link for full code
Full Code Git