我需要将文件和实体发送到服务器,我的服务器是Spring Boot应用程序:
@PostMapping("/upload")
public void upload(@RequestParam("dto") MyDto dto,
@RequestParam("file") MultipartFile file) {
...
}
MyDto.java:
@Getter
@Setter
@JsonIgnoreProperties(ignoreUnknown = true)
public class MyDto implements Serializable {
private String f1;
private String f2;
}
我的客户:
FormDataMultiPart formDataMultiPart = new FormDataMultiPart();
FileDataBodyPart fileDataBodyPart = new FileDataBodyPart("file",
new File("C:/dev/test.txt"),
MediaType.APPLICATION_OCTET_STREAM_TYPE);
MyDto dto = new MyDto();
dto.setF1("f1");
dto.setF2("f2");
final FormDataMultiPart multipart = (FormDataMultiPart) formDataMultiPart
.field("dto", dto, MediaType.APPLICATION_JSON_TYPE) // if I change to string type works fine;
.bodyPart(fileDataBodyPart);
Response response = ClientBuilder.newClient()
.target(String.format("%s%s", "http://localhost:8080", "/api/upload"))
.register(MultiPartFeature.class)
.request(MediaType.APPLICATION_JSON)
.header("Authorization", "Bearer " + token.getToken())
.post(Entity.entity(multipart, multipart.getMediaType()));
响应-> InboundJaxrsResponse {context = ClientResponse {方法= POST,uri = http://localhost:8080/api/upload,status = 500,原因=内部服务器错误}}
那么,有人意识形态出了什么问题?
答案 0 :(得分:1)
您需要创建一个wrapper class
才能与表单中的file
和form data
一起获得bind
。
public class MyDtoWrapper implements Serializable {
private String f1;
private String f2;
private MultipartFile image;
}
控制器
@PostMapping("/api/upload/multi/model")
public ResponseEntity<?> multiUploadFileModel(@ModelAttribute MyDtoWrapper model) {
try {
saveUploadedFile(model.getImage()); // Create method to save your file or just do it here
formRepo.save(mode.getF1(),model.getF2()); //Save as you want as per requirement
} catch (IOException e) {
return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
}
return new ResponseEntity("Successfully uploaded!", HttpStatus.OK);
}
有关完整示例,请查看here。