![](/img/trans.png)
[英]How to consume multipart form data with a rest template in spring boot
[英]How to consume Request Body (JSON) along with multiple files (multipart/form-data) via REST API in Spring Boot?
我想为我的 spring 启动应用程序使用 API 中的 JSON 和文件(使用 Z38008ECFlux60CE)。 我尝试了互联网上推荐的多种方法( Article1 , Article2 , Article3 ),但它对我不起作用。 API 未命中并从Postman获得状态 415(不支持的媒体类型)。
Spring-Boot 版本: 2.5.3
Spring-Web/Webflux 版本: 5.3.9
员工:
@Data
@NoArgsConstructor
@AllArgsConstructor
public class Employee {
private String name;
private int age;
private int mobileNo;
private List<MultipartFile> files;
}
Controller:
@PostMapping(path = "employee", consumes = {MediaType.APPLICATION_JSON_VALUE, MediaType.MULTIPART_FORM_DATA_VALUE})
public Mono<Response> processEmployeeDocs(@RequestPart Employee request, @RequestPart List<MultipartFile> files) {
Employee employee = new Employee(request.getName(), request.getAge(), request.getMobileNo(), files);
return employeeService.processDocs(employee);
}
根据spring 文档,而不是使用 MultipartFile 使用 FilePart 来使用多部分内容
下面是工作代码片段
@PostMapping(path = "employees", consumes = {MediaType.APPLICATION_JSON_VALUE, MediaType.MULTIPART_FORM_DATA_VALUE})
public Mono<ResponseEntity<Response>> processEmployeeDocs(@RequestPart Employee request, @RequestPart Flux<FilePart> files) {
log.info("processing request {}", request);
return files.flatMap(part -> part.transferTo(Paths.get("temp", File.separator, part.filename())))
.then(employeeService.processDocs(request))
.then(Mono.just(ResponseEntity.ok().build()));
}
上面的代码会将文件保存在“temp”目录中。 您可以使用这些文件来处理您的逻辑。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.