简体   繁体   中英

Spring boot controller - Upload Multipart file and Java Object,Angular 4,7

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 {

}

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. 邮差

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: 在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM