我想创建一个API,它可以将参数作为multipart文件和JSON对象(@RequestBody)。请在调用此API时找到以下代码段,我收到415 HTTP错误。如果我删除“@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
}
答案 0 :(得分:5)
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
答案 1 :(得分:0)
Spring Roo 2.0.0.M3包括对REST API自动搭建的支持。
有关完整信息,请参阅参考手册中的REST API。
请注意,M3版本会生成可能在较新版本中更改的工件,因此如果使用RC1或更高版本打开它,项目可能无法自动升级。
愿部队与你同在。
答案 2 :(得分:0)
使用@RequestPart注释参数时,该部分的内容将通过HttpMessageConverter传递,以考虑到请求部分的“ Content-Type”来解析方法参数。这类似于@RequestBody根据常规请求的内容来解析参数的操作。
因此,我们可以将@Requestbody解析为@RequestPart的“ abaghel”,并且reportData必须是一个json文件。
答案 3 :(得分:-1)
接收json对象和通用文件的post方法示例:
public ResponseEntity<Resource> postGenerateReport(@RequestPart GenerateReportDTO, generateReportDTO, @RequestPart MultipartFile jxhtmlReport)
对于 PostMan 设置(或curl或任何其他REST测试实用程序),您只需添加包含2个元素的表单数据请求:
Key:generateReportDTO
,Value:
文件,扩展名为.json (以及与对象兼容的内容)Key:jxhtmlReport
,Value:
只是任何文件。Gl