使用相同方法spring boot Rest支持multipart/form-data和application/json的方法有以下几种:
@PostMapping("/upload")
public String uploadFile(@RequestParam("file") MultipartFile file, @RequestParam("data") String data) {
// 上传文件逻辑
// 解析json数据逻辑
return "success";
}
@PostMapping("/upload")
public String uploadFile(@RequestPart("file") MultipartFile file, @RequestPart("data") String data) {
// 上传文件逻辑
// 解析json数据逻辑
return "success";
}
@Configuration
public class WebMvcConfig extends WebMvcConfigurerAdapter {
@Override
public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
converters.add(new MyHttpMessageConverter());
super.configureMessageConverters(converters);
}
}
public class MyHttpMessageConverter extends AbstractHttpMessageConverter<Object> {
public MyHttpMessageConverter() {
super(MediaType.ALL);
}
@Override
protected boolean supports(Class<?> clazz) {
return true;
}
@Override
protected Object readInternal(Class<?> clazz, HttpInputMessage inputMessage) throws IOException, HttpMessageNotReadableException {
// 解析请求参数逻辑
return null;
}
@Override
protected void writeInternal(Object o, HttpOutputMessage outputMessage) throws IOException, HttpMessageNotWritableException {
// 处理响应逻辑
}
}
@PostMapping("/upload")
public String uploadFile(@RequestBody Object requestData) {
// 解析请求参数逻辑
return "success";
}
以上是使用相同方法spring boot Rest支持multipart/form-data和application/json的几种方法,根据实际需求和个人喜好选择适合的方法即可。
领取专属 10元无门槛券
手把手带您无忧上云