我正在使用@RequestPart
注释来上传一些参数和图像文件。
但是我遇到了以下错误
Content type 'image/jpeg' not supported for bodyType=org.springframework.web.multipart.MultipartFile
下面是我的代码片段。如果我在触发 HTTP POST 请求时跳过文件部分。运行良好。
仅在传递文件期间。我收到错误。
@PostMapping(value = "document/uploadFile", consumes = {"multipart/form-data"})
public void uploadFile(@RequestPart(value = "name", required = true) String name,
@RequestPart(value = "fileType", required = true) String fileType,
@RequestPart(value = "file",required = false) MultipartFile file)
{
..logic to pick the data using POJO
}
application.yaml
## MULTIPART (MultipartProperties)
# Enable multipart uploads
spring:
servlet:
multipart:
enabled: true
# Threshold after which files are written to disk.
file-size-threshold : 2KB
# Max file size.
max-file-size: 10MB
# Max Request Size
max-request-size : 20MB
HTTP 生成的代码
POST /document/uploadFile HTTP/1.1
Host: localhost:8026
Content-Type: multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW
----WebKitFormBoundary7MA4YWxkTrZu0gW
Content-Disposition: form-data; name="name"
xyz
----WebKitFormBoundary7MA4YWxkTrZu0gW
Content-Disposition: form-data; name="fileType"
jpeg
----WebKitFormBoundary7MA4YWxkTrZu0gW
Content-Disposition: form-data; name="file"; filename="/C:/Users/XYZ/Pictures/Test.jpg"
Content-Type: image/jpeg
(data)
----WebKitFormBoundary7MA4YWxkTrZu0gW
来自 POSTMAN 的输入
postman 错误
{
"timestamp": "2020-01-09T11:17:49.398+0000",
"path": "/document/uploadFile",
"status": 415,
"error": "Unsupported Media Type",
"message": "Content type 'image/jpeg' not supported for bodyType=org.springframework.web.multipart.MultipartFile"
}
最佳答案
我怀疑这就是问题所在,但你在末尾缺少括号consumes = {“multipart/form-data”}
无论如何,使用您当前的代码,它应该可以完美地工作,我做了一个本地测试,所以您的问题可能在于您如何执行请求。
请务必将其作为 RequestHeader 添加到您的其余客户端中:Content-Type: multipart/form-data,或者如果您使用的是表单,则需要像这样添加它:
<form method="POST" action="/upload" enctype="multipart/form-data">
<input type="file" name="file"/>
<input type="name" name="name"/>
<input type="fileType" name="fileType"/>
<button type="submit">Submit</button>
</form>
关于java - Spring Boot 中的 "Content type ' 图像/jpeg ' not supported for bodyType=org.springframework.web.multipart.MultipartFile",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59646584/