Spring boot controller - Upload Multipart file and

2019-08-30 07:27发布

问题:

how to send data using Postman in example DTO ,mainly Multipart file data,Angular 4,7

data in Multipartfile in Example DTO

public class ExampleDTo {

    private MultipartFile image;

    private String name;
    private String description;

}

Controller Mapping

@PostMapping()
public ResponseEntity<?> saveExample(@RequestParam("dtoAnduploadingFiles") ExampleDTo  dtoAnduploadingFiles  ) throws IOException {

}

回答1:

One way to do this is to use multiple multiparts.

So for example if you use this controller:

@PostMapping
public void uploadFileWithData(
        @RequestPart ExampleDTo request,
        @RequestPart("file") final MultipartFile file){
    ...
}

note: ExampleDto should contain only fields of json payload, not MultipartFile

In Postman you should use then form-data and choose file which you want to upload and also file with json payload.



回答2:

You can do it like a normal multipart Form from Postman but you need to update your Mapping Method.

@PostMapping("/upload-file-form")
    public ResponseEntity<?> multiUploadFileModel(@ModelAttribute ExampleDTo model) {
        try {
            saveUploadedFile(model.getImage()); // Create method to save your file or just do it here
            formRepo.save(mode.getName(),model.getDescription()); //Save as per requirement 
        } catch (IOException e) {
            return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
        }
        return new ResponseEntity("Successfully uploaded!", HttpStatus.OK);
    }

For complete code example look here. And then you can test it on postman like this: