Отправить сущность и файл с FormDataMultiPart - PullRequest
0 голосов
/ 14 января 2019

Мне нужно отправить файл и сущность на мой сервер, мой сервер - приложение с весенней загрузкой:

@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 -> InboundJaxrsResponse {context = ClientResponse {method = POST, uri = http://localhost:8080/api/upload, status = 500, причина = внутренняя ошибка сервера}}

Итак, у кого-то есть идеи, что не так?

1 Ответ

0 голосов
/ 15 января 2019

Вам нужно создать 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);
}

Для полного примера смотрите здесь .

...