我们可以在 spring 中同时使用 multipart 和 @RequestBody 吗? [英] Can we use multipart and @RequestBody together in spring?
问题描述
我想创建一个可以将参数作为多部分文件和 JSON 对象 (@RequestBody) 的 API.请在调用此 API 时找到以下代码段.我收到 HTTP 415 Unsupported Media Type 错误.如果我删除 @RequestBody LabPatientInfo reportData
那么它工作正常.
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 Unsupported Media Type error. If I remove @RequestBody LabPatientInfo reportData
then it works fine.
@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 类.
following is LabPatientInfo class.
@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 对象..
while hitting API I am passing following JSON object with uploaded file..
{
"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 对象和多部分文件.
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 {
为了使用 curl 对其进行测试,您可以为 json 部分创建一个文件(<强>报告数据).例如,假设您创建了mydata.json"文件并将您的 json 负载粘贴到其中.并说您的 reportFile 是report.txt".现在您可以使用 curl 发送请求,如下所示.
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
这篇关于我们可以在 spring 中同时使用 multipart 和 @RequestBody 吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!