简体   繁体   中英

How to send multipart form data with json value in Spring Boot

Hi there, I want to send to postman a body with json and an image in formd-data...

I save the form-data image in a s3 bucket, the entity has as an string attribute that is the link of the image

Here my spring boot controller

@PostMapping(consumes = { "multipart/mixed", "multipart/form-data" }, produces = MediaType.APPLICATION_JSON_VALUE)
    public CharacterResponse createCharacter(@Valid @RequestBody CharacterRequest characterRequest, @RequestParam(value = "file", required = false) MultipartFile file) {
        CharacterDto characterDto = mapper.map(characterRequest, CharacterDto.class);
        CharacterDto createdCharacter = characterService.createCharacter(characterDto, file);
        return mapper.map(createdCharacter, CharacterResponse.class);
    }

I have already tried with @RequestParam and @RequestPart for the MultiPartFile... I get this error:

"Content type 'multipart/form-data;boundary=--------------------------340232294957024834187036;charset=UTF-8' not supported"

From my point of view you could try this:

in method attributes use @RequestPart with values. And also you should use the same structure in your client (for ex. in postman for each part you should explicitly set content-type, auto content-type works not perfect. For keys you should use values from @RequestPart, and in values just put your payload)

@PostMapping(consumes={ MediaType.MULTIPART_FORM_DATA_VALUE }, 
produces=MediaType.APPLICATION_JSON_VALUE)
public CharacterResponse createCharacter(
    @Valid @RequestPart("body") CharacterRequest characterRequest,
    @RequestPart(value="file", required=false) MultipartFile file)
{
    //code
}

Just using @RequestParam for both parameter should do the job.

@PostMapping("/api/path")
public CharacterResponse createCharacter(@Valid @RequestParam CharacterRequest characterRequest, @RequestParam(required = false) MultipartFile file) {
    CharacterDto characterDto = mapper.map(characterRequest, CharacterDto.class);
    CharacterDto createdCharacter = characterService.createCharacter(characterDto, file);
    return mapper.map(createdCharacter, CharacterResponse.class);
}

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