我想创建一个 API,它可以将参数作为多部分文件和 JSON 对象 (@RequestBody)。请在调用此 API 时找到以下代码段。我得到 HTTP 415 Unsupported Media Type error .如果我删除 @RequestBody LabPatientInfo reportData
然后它工作正常。
@RequestMapping(value={"/lab/saveReport"}, method={RequestMethod.POST},
consumes={"multipart/form-data"}, headers={"Accept=application/json"})
@ResponseBody
public ResponseEntity<String>
saveReport(@RequestParam(value="reportFile") MultipartFile reportFile,
@RequestBody LabPatientInfo reportData) throws IOException {
HttpHeaders headers = new HttpHeaders();
headers.add("Content-Type", "application/json; charset=utf-8");
logger.info("in Lab Save Report");
logger.info("Report Data {} ", reportData);
//logger.info("Request BODY {} ", request.getAttribute("data"));
return new ResponseEntity<String>(HttpStatus.OK);
}
以下是 LabPatientInfo 类。
@RooJson(deepSerialize = true)
@RooToString
public class LabPatientInfo {
private String firstName;
private String phoneNumber;
private String DateOfBirth;
private Integer age;
private String gender;
private String refferedBy;
private String reportfile;
private String reportType;
private String reportDate;
private String purpose;
private String followUpDate;
private List<ReportDataInfo> analytes;
在点击 API 时,我正在传递以下带有上传文件的 JSON 对象..
{
"firstName":"abc",
"phoneNumber":"898989",
"DateOfBirth":"asas",
"age":"asas",
"gender":"asas",
"refferedBy":"asas",
"reportfile":"asas",
"reportType":"asas",
"reportDate":"asas",
"purpose":"asas",
"followUpDate":"asas",
"analytes":null
}
最佳答案
您可以像下面这样使用@RequestPart
。这将同时支持 json 对象和多部分文件。
@ResponseBody
public ResponseEntity<String>
saveReport(@RequestPart (value="reportFile") MultipartFile reportFile,
@RequestPart LabPatientInfo reportData) throws IOException {
为了使用 curl 进行测试您可以为您的 json 部分创建一个文件 (reportData)。例如,假设您创建了“mydata.json”文件并将您的 json 有效负载粘贴到其中。并假设您的 reportFile 是“report.txt”。现在您可以像下面这样使用 curl 发送请求。
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
关于java - multipart和@RequestBody在spring可以一起用吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40924649/