Spring启动发送RequestBody和RequestParam

时间:2018-03-11 06:38:36

标签: java spring multipartform-data

我正在装箱api,我需要在一个请求中发送Json(作为对象)和图像文件。所以我就是这样做的。

@PostMapping("/upload")
public String singleFileUpload(@RequestBody Item item, @RequestParam("file") MultipartFile file) {
   // logic
}

以及我如何使用Postman

测试此方法

enter image description here

这是标题 enter image description here

这里也是我的项目对象

{
    "title": "useruser",
    "description": "Woodfsdfw",
    "img": "www.gosdfsdfsdfsdfog.elt",
    "lat": 45.48745,
    "lng": 96.5651655,
    "user": {
        "name": "Jerry",
        "img" : "sdfsdfdfsdf",
        "email": "jrry@gmail.com"
    }
}

所以这就是我从服务器获得的响应

 {
    "timestamp": 1520750026769,
    "status": 415,
    "error": "Unsupported Media Type",
    "exception": "org.springframework.web.HttpMediaTypeNotSupportedException",
    "message": "Content type 'multipart/form-data;boundary=----WebKitFormBoundaryYzp58riGtVnLl7mI;charset=UTF-8' not supported",
    "path": "/api/upload"
}

我一直在努力奋斗4个小时。知道怎么解决这个问题吗? 编辑 在我使用Content-Type multipart/form-data后,我收到此错误

{
    "timestamp": 1520750811814,
    "status": 500,
    "error": "Internal Server Error",
    "exception": "org.springframework.web.multipart.MultipartException",
    "message": "Could not parse multipart servlet request; nested exception is java.io.IOException: org.apache.tomcat.util.http.fileupload.FileUploadException: the request was rejected because no multipart boundary was found",
    "path": "/api/upload"
}

1 个答案:

答案 0 :(得分:2)

您应该使用@RequestPart作为输入参数,例如:

@PostMapping("/upload", consumes = {"multipart/form-data"})
public String singleFileUpload(@RequestPart("item") Item item, @RequestPart("file") MultipartFile file) {
   // logic
}

使用curl请求验证

curl -H 'Content-Type: multipart/form-data' -F item='{"key": "value"};type=application/json' -F file='@/path/to/file;type=application/octet-stream' http://'your-url' --trace-ascii -

打印卷曲曲线输出,如果它仍然不适合你。