我想在一个帖子请求中发送一个文件和一个json模型。
我的请求映射如下所示:
@PostMapping("{id}/files") public MyOutput create(@PathVariable String id, @RequestPart("request") MyInput input, @RequestPart("file") MultipartFile file) { // ... }
我收到的错误:
{ "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" }
我的WebConfig:
@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()); }
您可以尝试使用代替
@RequestPart("file") MultipartFile file
用这个
@RequestParam(value = "file",required = false) MultipartFile file
并确保将请求类型设置为multipart / form-data。可以从邮递员的标题标签中进行设置。
如果需要使用多部分文件发送另一个对象,则可以将其作为字符串发送,然后可以将其转换为后端的对象。
@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(); } }