Can we use multipart and @RequestBody together in spring?

后端 未结 4 1038
醉酒成梦
醉酒成梦 2021-02-20 06:00

I want to create a API which can have parameter as multipart file and JSON object (@RequestBody). Please find following snippet while calling this API. I am getting HTTP 415 Uns

相关标签:
4条回答
  • 2021-02-20 06:22

    An example of a post method which receives a json object and a generic file:

    public ResponseEntity<Resource> postGenerateReport(@RequestPart GenerateReportDTO, generateReportDTO, @RequestPart MultipartFile jxhtmlReport)
    

    For the PostMan setup (or curl or anyother REST test utility) you just have to add form-data request with 2 elements:

    1. Key:generateReportDTO, Value: File with .json extension (and compatible content with the object)
    2. Key:jxhtmlReport, Value: just any file.

    Gl

    0 讨论(0)
  • 2021-02-20 06:23

    When a parameter is annotated with @RequestPart the content of the part is passed through an HttpMessageConverter to resolve the method argument with the 'Content-Type' of the request part in mind. This is analogous to what @RequestBody does to resolve an argument based on the content of a regular request.

    so, we can parse @Requestbody as @RequestPart as "abaghel" and reportData need to be a json file.

    0 讨论(0)
  • 2021-02-20 06:42

    You can use @RequestPart like below. This will support both json object and multipart file.

    @ResponseBody
    public ResponseEntity<String>
    saveReport(@RequestPart (value="reportFile") MultipartFile reportFile,
               @RequestPart LabPatientInfo reportData) throws IOException {
    

    In order to test it using curl you can create one file for your json part (reportData). Say for example you create "mydata.json" file and paste your json payload in it. And say your reportFile is "report.txt". Now you can send request using curl like below.

    curl -v -H "Content-Type:multipart/form-data" -F "reportData=@mydata.json;type=application/json" -F "reportFile=@report.txt;type=text/plain"  http://localhost:8080/MyApp/lab/saveReport
    
    0 讨论(0)
  • 2021-02-20 06:43

    Spring Roo 2.0.0.M3 includes support for automatic scaffolding of a REST API.

    For complete information, see the REST API in the reference manual.

    Note the M3 version generate artifacts that could change in newer versions, so your project might not upgrade automatically if you open it with RC1 or above.

    May the Force be with you.

    0 讨论(0)
提交回复
热议问题