我们如何接受包含多个部分的请求正文?

时间:2019-06-24 11:17:57

标签: java spring-boot file-upload postman multipartform-data

我正在尝试使用请求正文和四个多部分文件进行发布请求。

我已经共享了api

@PostMapping(value = "/deductee-master", consumes = MediaType.ALL_VALUE)
public ResponseEntity <DeducteeMaster> createDeductee(@RequestBody DeducteeMasterDTO deducteeMasterDTO, @RequestParam("trcFile") MultipartFile trcFile, @RequestParam("tenFFile") MultipartFile tenFFile, @RequestParam("wpeFile") MultipartFile wpeFile, @RequestParam("noPEFile") MultipartFile noPEFile)
throws InvalidKeyException, URISyntaxException, StorageException, IOException {
    DeducteeMaster result = deducteeMasterService.save(deducteeMasterDTO, trcFile, tenFFile, wpeFile, noPEFile);
    return ResponseEntity.created(new URI("/api/deductee-master/" + result.getKey().getId()))
        .headers(HeaderUtil.createEntityCreationAlert(ENTITY_NAME, result.getKey().getId().toString()))
        .body(result);
}
{
    "timestamp": "2019-06-24T11:04:40.076+0000",
    "status": 415,
    "error": "Unsupported Media Type",
    "message": "Content type 'multipart/form-data;boundary=--------------------------603218794646006873131102;charset=UTF-8' not supported",
    "path": "/api/deductee-master"
}

1 个答案:

答案 0 :(得分:0)

使用@RequestPart,并且由于您尝试同时发送RequestBodyFiles,因此必须将其附加到FormData上以发送数据。

@RequestMapping(value = "/foo", method = RequestMethod.POST, consumes = "multipart/form-data")
public ResponseEntity<DeducteeMaster> createDeductee(@RequestPart("data") DeducteeMasterDTO deducteeMasterDTO,
            @RequestPart("trcFile") MultipartFile trcFile,
            @RequestPart("tenFFile") MultipartFile tenFFile,
            @RequestPart("wpeFile") MultipartFile wpeFile,
            @RequestPart("noPEFile") MultipartFile noPEFile)
            throws InvalidKeyException, URISyntaxException, StorageException, IOException {

     //LOGIC
     return // ...;

    }

如果要使用CurL进行测试

curl -i -H "Content-Type:multipart/form-data" 
             -F "data =@test.json;type=application/json" 
             -F "trcFile =@test.csv;type=application/csv"
             -F "tenFFile =@test1.csv;type=application/csv"
             -F "wpeFile =@test2.csv;type=application/csv"
             -F "noPEFile =@test3.csv;type=application/csv"
             http://localhost:8080/foo

如果要通过Angular,React或任何javascript lang发送发布请求,请尝试使用FormData。将数据追加到formData