Thursday, 9 June 2016

File Upload using Spring RestFul service

File Upload using Spring RestFul service

In this blow we will try to upload file file using Spring RestFul service.

First we need to register a bean in spring configuration XMl file for MultipartResolver that Spring support for uploading.
Here we have used CommonsMultipartResolver provided by spring framework to upload a file

Example:
<bean id="multipartResolver"              class="org.springframework.web.multipart.commons.CommonsMultipartResolver"
p:defaultEncoding="utf-8"/>

Now create a controller and annotating with proper path.
Example:
@RequestMapping(value = "/image/ imageid/{imageid}", method = RequestMethod.POST)
  public String imageUpload(HttpServletRequest request,
      @RequestParam("imagefile") MultipartFile file) throws IOException {    
    InputStream stream = file.getInputStream();
            String fileName = file.getOriginalFilename();          
            System.out.println(“File name: “ + fileName);
            /*
            Now you have InputStream, file name and other information available so, you can save where you want
            */
    return "SUCCESS";
  }


To the created service we can test it using Postmaster app plugin of Chrome.


No comments:

Post a Comment