17 Ocak 2017 Salı

Uploading File/Image to Spring-MVC REST Service

In this article I'll show how to implement a RESTful Web Service with Spring-MVC that accepts file as request parameter and how to test it using Postman.

First add multipartResolver bean to your spring configuration file:

    <bean id="multipartResolver"
        class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
    </bean>

Below is how I made my service to accept multipart form data:

@RestComtroller
@RequestMapping("/profile")
public class UserProfileController {

    @Autowired
    StorageService storageService;

    @RequestMapping(value="/post/image", method = RequestMethod.POST, consumes = "multipart/form-data")
    public OperationResult<Boolean> postUserImage(@RequestParam("file") MultipartFile file) {
        OperationResult<Boolean> result = null;
        try {
            String fileName = file.getOriginalFileName();
            this.storageService.store(file, fileName);
            result = new OperationResult<>(true);
        }
        catch (Exception e) {
            // handle exception here
            result = new OperationResult<>(ErrorCode.CannotStoreFile, "Error title", "Error message");
        }
        return result;
    }
}

In this code, the OperationResult is just a type that I coded for encapsulating response data. StorageService on the other hand is another class I coded which handles saving files into physical storage.

The important thing here is to add "consumes" attribute to @RequestMapping annotation and using @RequestParam annotation for the MultipartFile instead of @RequestBody.

Also don't forget to add commons-io and commons-fileupload dependencies. If you are using maven, just add the following dependencies to your pom.xml (change the version):

    <dependency>
        <groupId>commons-fileupload</groupId>
        <artifactId>commons-fileupload</artifactId>
        <version>${commons.version}</version>
    </dependency>

    <dependency>
        <groupId>org.apache.commons</groupId>
        <artifactId>commons-io</artifactId>
        <version>${commons.io.version}</version>
    </dependency>


Now, let's call this service from Postman.

Postman is a great tool for testing your APIs. If you haven't checked yet, see https://www.getpostman.com/


  • While testing this service, do not send "Content-Type" header parameter. 
  • From the body section, choose form-data and add a parameter. 
  • The name of the parameter should be same with the name of the parameter of your service method. In this case, the name of the parameter is "file".
  • Change the type of the parameter to be "File"
  • Choose the file to be uploaded

Send your request and that's it.



Hiç yorum yok:

Yorum Gönder