简体   繁体   中英

Multi-Part Request

I have an application which handles Multipart Request in below format.

POST .... HTTP/1.1 
. . . 
Accept:multipart/form-data 
...
---boundary123 Content-type:application/octet-stream content-Disposition: 
form-data filenale="payload.txt" name="someuniquename" 
... 
[paylaod content](this is in xml format) 
---boundary123 content-type:application/json content-Disposition:form-data 
name="someuniquname1" 
{ 
... 
ID:"999"
}

---boundary123

and here is my my controller part.

@Restcontroller 
Class A{ 
@RequestMapping(value = "/a/b/c", method = RequestMethod.POST,  consumes= 
MediaType.MULTIPART_FORM_DATA_VALUE, 
produces=MediaType.APPLICATION_JSON_VALUE)

public @ResponseBody static void MyController(@RequestParam("file") 
List<MultipartFile> files) {
}

Is this controller can parse both parts by identifying content-type(xml and json, no order) if I am receiving single multi-part file.If not Can you suggest format of controller for the same.

The way to achieve this would be to use the part boundry name with the RequestPart annotation:

@Restcontroller 
Class A {

    @RequestMapping(
            value = "/a/b/c",
            method = RequestMethod.POST, 
            consumes = MediaType.MULTIPART_FORM_DATA_VALUE, 
            produces = MediaType.APPLICATION_JSON_VALUE
    )
    public @ResponseBody void myController(@RequestPart("someuniquname") SomePojo xmlPart, @RequestPart("someuniquname1") SomeOtherPojo jsonPart) {
        // ...
    }
// ...
}

Use following to get the FormData in your Controller.

RequestMapping(value = "/yourPath", method = RequestMethod.POST)
public @ResponseBody Object upload(MultipartHttpServletRequest request, HttpServletResponse response) throws IOException {
    //Get your form fields...
    final String ID= request.getParameter('ID');
    //and so on......

    //Get your files.
    Iterator<String> iterator = request.getFileNames();
    MultipartFile multipartFile = null;
    while (iterator.hasNext()) {
        multipartFile = request.getFile(iterator.next());
        //do something with the file.....
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM