[英]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...您好,我想向 postman 发送带有 json 的主体和形成数据中的图像...
I save the form-data image in a s3 bucket, the entity has as an string attribute that is the link of the image我将表单数据图像保存在 s3 存储桶中,实体具有作为图像链接的字符串属性
Here my spring boot controller这里我的 spring 启动 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:我已经尝试过使用 @RequestParam 和 @RequestPart 的 MultiPartFile ...我收到此错误:
"Content type 'multipart/form-data;boundary=--------------------------340232294957024834187036;charset=UTF-8' not supported" “内容类型 'multipart/form-data;boundary=--------------------------340232294957024834187036;charset=UTF-8' 不支持”
From my point of view you could try this:从我的角度来看,你可以试试这个:
in method attributes use @RequestPart with values.在方法属性中使用带有值的@RequestPart。 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)而且您还应该在您的客户端中使用相同的结构(例如,在 postman 中,您应该明确设置每个部分的内容类型,自动内容类型并不完美。对于键,您应该使用来自 @RequestPart 的值,而在值中只是把你的有效载荷)
@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.只需将@RequestParam
用于两个参数就可以完成这项工作。
@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);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.