Java 使用FormDataMultiPart发送实体和文件

Java 使用FormDataMultiPart发送实体和文件,java,spring-boot,jersey,jersey-client,Java,Spring Boot,Jersey,Jersey Client,我需要向我的服务器发送文件和实体,我的服务器是spring boot应用程序: @PostMapping("/upload") public void upload(@RequestParam("dto") MyDto dto, @RequestParam("file") MultipartFile file) { ... } MyDto.java: @Getter @Setter @JsonIgnoreProperties(ignoreUn

我需要向我的服务器发送文件和实体,我的服务器是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()));
response->inboundjaxrssponse{context=ClientResponse{method=POST,uri=,status=500,reason=Internal Server Error}


因此,有人有了一个想法,怎么了?

您需要创建一个
包装类
来获取
文件
以及
表单数据
,并将其与表单绑定

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);
}
@PostMapping(“/api/upload/multi/model”)
公共响应多上传文件模型(@modeldattribute MyDtoWrapper model){
试一试{
saveUploadedFile(model.getImage());//创建方法来保存文件,或者在此处执行此操作
formRepo.save(mode.getF1(),model.getF2());//根据需要按需保存
}捕获(IOE异常){
返回新的响应属性(HttpStatus.BAD_请求);
}
返回新的响应状态(“已成功上载!”,HttpStatus.OK);
}

查看完整的示例。

我忘了在客户端使用jersey上传数据。那么,客户端上的spring Multipart类等价于什么呢?我尝试了FormDataMultiPart和FormDataMultiPart,但在这两种情况下都出现了MessageBodyWriter错误。仍在寻找解决方案,但考虑使用类似于:@RequestParam(“f1)字符串f1、RequestParam(“f2)字符串f2、@RequestParam(“文件”)多部分文件文件的代码,似乎是一种气味,但可以无缝工作。在这种情况下,我认为您需要创建不同的参数。我建议你阅读这个详细的答案