使用FormDataMultiPart发送实体和文件

时间:2019-01-14 18:36:09

标签: 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(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,原因=内部服务器错误}}

那么,有人意识形态出了什么问题?

1 个答案:

答案 0 :(得分:1)

您需要创建一个wrapper class才能与表单中的fileform 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