Tuesday 6 October 2015

Upload image in Spring MVC Application


Step-1

  pom.xml
 <dependency>
                   <groupId>commons-fileupload</groupId>
                   <artifactId>commons-fileupload</artifactId>
                   <version>1.2.2</version>
          </dependency>
           
          <dependency>
                   <groupId>commons-io</groupId>
                   <artifactId>commons-io</artifactId>
                   <version>1.3.2</version>
          </dependency>



 Step-2
  
 for uploading image enctype="multipart/form-data"
 commandName is mandatory 

<ff:form name="F1" onSubmit="return dil(this)" action="create.htm" method="post"
 commandName="fcustomer" enctype="multipart/form-data">


<ff:form>



Step-3:-

Add this html tag in jsp

<tr><td>Upload Photo:</td><td> <input type="file" name="photo"/></td></tr>    


Step-4:-
Add one spring bean for image upload in spring application context file

<?xml version="1.0" encoding="UTF-8"?>
          xsi:schemaLocation="
                   http://www.springframework.org/schema/beans
                   http://www.springframework.org/schema/context
<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="4000000"/>
    </bean>
 </beans>        



Step-5:-

//It converts your upload file into byte array form after it
//it is populated in customer java object
 @InitBinder
 public void initBinder(WebDataBinder binder) {
                   // to actually be able to convert Multipart instance to byte[]
                   // we have to register a custom editor
                   binder.registerCustomEditor(byte[].class,
                                      new ByteArrayMultipartFileEditor());
                   // now Spring knows how to handle multipart object and convert them
 }


Step-6
Accessing populated pojo in spring controller
using @ModelAttribute

  @RequestMapping(value = "/cust/save.do", method = RequestMethod.POST)
public String saveCustomerAction(
@Valid @ModelAttribute("ccustomer") Customer customer,
BindingResult bindingResult, Model model) {
if (bindingResult.hasErrors()) {
logger.info("Returning custSave.jsp page"); return "custSave";
}
logger.info("Returning custSaveSuccess.jsp page");
model.addAttribute("customer", customer);
customers.put(customer.getEmail(), customer);
return "custSaveSuccess";
}




No comments:

Post a Comment