Reputation: 3105
I'm crating api and I need to send Json (as object) and image file in one request. So here's how I do it.
@PostMapping("/upload")
public String singleFileUpload(@RequestBody Item item, @RequestParam("file") MultipartFile file) {
// logic
}
and here how I test this method with Postman
also here's my item object
{
"title": "useruser",
"description": "Woodfsdfw",
"img": "www.gosdfsdfsdfsdfog.elt",
"lat": 45.48745,
"lng": 96.5651655,
"user": {
"name": "Jerry",
"img" : "sdfsdfdfsdf",
"email": "[email protected]"
}
}
So here what I get from server as a response
{
"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"
}
I've been struggling with this for 4 hours. Any idea how to fix that?
EDIT
after I used Content-Type multipart/form-data
I get this error
{
"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"
}
Upvotes: 1
Views: 8405
Reputation: 700
You should use @RequestPart
for both your input parameters like:
@PostMapping("/upload", consumes = {"multipart/form-data"})
public String singleFileUpload(@RequestPart("item") Item item, @RequestPart("file") MultipartFile file) {
// logic
}
Use a curl request to verify
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 -
Print the curl trace output if it still doesn't work for you.
Upvotes: 3