2016-12-02 2713 views
1

我想创建一个API,它可以有参数作为多部分文件和JSON对象(@RequestBody)。调用此API时请找到以下代码片断我得到415 HTTP错误。如果我删除“@RequestBody LabPatientInfo reportData”,那么它工作正常。春天我们可以一起使用multipart和@RequestBody ..吗?

@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 
} 

回答

2

您可以使用@RequestPart像下面。这将支持json对象和多部分文件。

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

为了使用curl来测试它,你可以为你的JSON部分(reportData)创建一个文件。比如说你创建“mydata.json”文件并粘贴你的json载荷。并说你的报告文件是“report.txt”。现在你可以使用下面的curl发送请求。

curl -v -H "Content-Type:multipart/form-data" -F "[email protected];type=application/json" -F "[email protected];type=text/plain" http://localhost:8080/MyApp/lab/saveReport 
+0

是的,这将工作 –

+0

嘿我使用上面的代码,现在得到HTTP状态400 - 所需的请求部分'reportData'不存在。 – Mayur

+0

@mayur你如何发送请求?你可以尝试使用卷曲。我已经用细节更新了我的答案。请检查。 – abaghel

0

Spring Roo 2.0.0.M3支持REST API的自动脚手架。

有关完整信息,请参阅参考手册中的REST API

请注意,M3版本生成的工件在新版本中可能会发生变化,因此如果您使用RC1或更高版本打开它,项目可能不会自动升级。

愿力量与你同在。

相关问题