fue*_*a22 4 java rest spring-boot
我想在一个帖子请求中发送一个文件和一个 json 模型。
我的请求映射如下所示:
@PostMapping("{id}/files")
public MyOutput create(@PathVariable String id, @RequestPart("request") MyInput input, @RequestPart("file") MultipartFile file) {
// ...
}
Run Code Online (Sandbox Code Playgroud)
我收到的错误:
{
"timestamp": "Feb 7, 2019, 3:18:50 PM",
"status": 415,
"error": "Unsupported Media Type",
"message": "Content type 'application/octet-stream' not supported",
"trace": "org.springframework.web.HttpMediaTypeNotSupportedException: Content type 'application/octet-stream' not supported...,
"path": "/tests/12345/files"
}
Run Code Online (Sandbox Code Playgroud)
邮递员请求:http : //imgshare.free.fr/uploads/62f4cbf671.jpg
我的网络配置:
@Override
public void configureMessageConverters(final List<HttpMessageConverter<?>> converters) {
GsonBuilder builder = new GsonBuilder();
Gson gson = builder.setPrettyPrinting().create();
final GsonHttpMessageConverter msgConverter = new GsonHttpMessageConverter();
msgConverter.setGson(gson);
msgConverter.setDefaultCharset(StandardCharsets.UTF_8);
converters.add(msgConverter);
converters.add(new StringHttpMessageConverter());
//
converters.add(new ByteArrayHttpMessageConverter());
converters.add(new FormHttpMessageConverter());
converters.add(new ResourceHttpMessageConverter());
}
Run Code Online (Sandbox Code Playgroud)
你可以尝试使用而不是这个
@RequestPart("file") MultipartFile file
Run Code Online (Sandbox Code Playgroud)
用这个
@RequestParam(value = "file",required = false) MultipartFile file
Run Code Online (Sandbox Code Playgroud)
并确保将请求类型设置为 multipart/form-data 您可以在 headers 选项卡中从邮递员那里设置它。
如果您需要使用多部分文件发送另一个对象,您可以将其作为字符串发送,然后您可以在后端将其转换为对象。
@PostMapping("/upload")
public void uploadFile(@Nullable @RequestParam(value = "file",required = false) MultipartFile file,
@RequestParam(value = "input", required = false) String st)
{
ObjectMapper om = new ObjectMapper();
MyInput input = null;
try {
input = om.readValue(st, MyInput.class); //string st -> MyInput input
} catch (IOException e) {
e.printStackTrace();
}
}
Run Code Online (Sandbox Code Playgroud)
邮递员请求示例:
| 归档时间: |
|
| 查看次数: |
12372 次 |
| 最近记录: |