JR Utily
JR Utily

Reputation: 1852

Curl / Spring MVC : POST gives MissingServletRequestParameterException

I'm using Spring MVC 4 with @RestController to receive a form post. I've made it following the tips given here and its works well with Spring Test MockMvc.

However, I'd like now to POST things to my server with curl, and I don't find a way to be accepted. I always get the following exception : org.springframework.web.bind.MissingServletRequestParameterException: Required String parameter 'file' is not present

I've tried to mix with the @Consumes from Spring and the -H option from curl, but it doesn't seem to be relevant.

So, given the following @RestController, what curl command should be executed to post something ?

@RestController
@RequestMapping(value = ONE_COLLECTION)
public class OneCollectionController {

    @RequestMapping(method = RequestMethod.POST )
    public RESTDocumentListElement uploadDocument( @RequestParam("file") MultipartFile file, @RequestPart("data") NewDocumentData documentData ) throws IOException {
       // -- code here --
    }
}

The last command I've tried (and got exception):

curl http://host/oneCollection -X POST -F "file=@./myFile.txt" -H "Content-Type: multipart/form-data" -F 'data={"name"="myName"}'

The working Spring Test MockMvc code:

// ...

MockMultipartFile firstFile = new MockMultipartFile("file", "dummyFile.txt", "text/plain", "blahblah".getBytes());
MockMultipartFile jsonFile = new MockMultipartFile("data", "", "application/json", TestUtil.convertObjectToJsonString(documentData).getBytes() );

ResultActions result = mockMvc.perform(fileUpload(ONE_COLLECTION)
                    .file(firstFile)
                    .file(jsonFile)
    );

// ...

Upvotes: 3

Views: 4845

Answers (1)

JR Utily
JR Utily

Reputation: 1852

Figured it out !

I've changed the controller method mapping for:

 @RequestMapping(method = RequestMethod.POST, consumes = {"multipart/*"})
 public RESTDocumentListElement uploadDocument( @RequestPart("file") MultipartFile file, @RequestPart("data") NewDocumentData documentData ) throws IOException {

But the tricky part was for the MultipartResolver in my JavaConfig, I was using the standard StandardServletMultipartResolver provided by Servlet 3, and had to switch to the Apache Commons one:

@Bean
public MultipartResolver multipartResolver() {
    CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver();
    return multipartResolver;
}

so I needed to had some dependency in maven too

<!-- Apache Commons -->
<dependency>
    <groupId>commons-fileupload</groupId>
    <artifactId>commons-fileupload</artifactId>
    <version>1.3</version>
</dependency>

and finally, the curl command was:

curl http://host/oneCollection -X POST -F 'file=@./firstFile.txt;type=text/plain' -F 'data={"collection":"toto"};type=application/json' -H "Content-Type: multipart/form-data" 

Upvotes: 4

Related Questions