我正在使用 Spring Boot,我想使用 Swagger UI 发送带有 json 的 MultipartFile,但我收到错误
'application/octet-stream' error not supported
,如果我使用 Postman 工作得很好。
@ResponseBody
@RequestMapping(value = "/upload", method = RequestMethod.POST,
produces = { "application/json" },
consumes = { "multipart/form-data" })
public String hello(
@RequestPart(value = "file") MultipartFile file,
@RequestPart("grupo") Grupo grupo) {
if (file != null) {
logger.info("File name: " + file.getOriginalFilename());
}
logger.info(grupo.toString());
return grupo.toString();
}
我该如何解决这个问题?
按照@Vishal Zanzrukia 提供的链接
我添加了这个配置:
import java.util.ArrayList;
import org.springframework.boot.info.BuildProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.MediaType;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
@Configuration
public class OpenApiConfig {
/**
*
* This method is needed to allow sending multipart requests. For example, when an item is
* created together with an image. If this is not set the request will return an exception with:
*
* Resolved [org.springframework.web.HttpMediaTypeNotSupportedException: Content-Type
* 'application/octet-stream' is not supported]
*
* @param converter
*/
public OpenApiConfig(MappingJackson2HttpMessageConverter converter) {
var supportedMediaTypes = new ArrayList<>(converter.getSupportedMediaTypes());
supportedMediaTypes.add(new MediaType("application", "octet-stream"));
converter.setSupportedMediaTypes(supportedMediaTypes);
}
...
现在它似乎可以按预期工作,代码如下:
Controller.java
@PostMapping(path = "/", consumes = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<Item> createItemWithoutImage(@Valid @RequestBody Item item) {
Item createdItem = itemService.createItem(item);
return ResponseEntity.status(HttpStatus.CREATED).body(createdItem);
}
@PostMapping(path = "/", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
public ResponseEntity<Item> createItem(@Valid @RequestPart Item item,
@RequestPart(name = "image", required = false) MultipartFile imageFile) {
// DO Something with the image
Item createdItem = itemService.createItem(item);
return ResponseEntity.status(HttpStatus.CREATED).body(createdItem);
}
要使用 multipartFile 发送 json,请使用注释
@Parameter
,类型为 "string"
,格式为 "binary"
,这样您就可以发送格式为 json 的文件。
@Parameter(schema =@Schema(type = "string", format = "binary"))
然后就变成这样了。
@PostMapping(value = "/test", consumes = MediaType.MULTIPART_FORM_DATA_VALUE )
public ResponseEntity<Void> saveDocu2ment(
@RequestPart(value = "personDTO") @Parameter(schema =@Schema(type = "string", format = "binary")) final PersonDTO personDTO,
@RequestPart(value = "file") final MultipartFile file) {
return null;
}