我想上传文件,但仍然收到“无法转换请求:找不到适用于预期类型[org.springframework.web.multipart.MultipartFile]的合适的HttpMessageConverter”
如何解决此问题?
private RequestMapping createMappingFile(HttpMethod[] method, String... path) {
RequestMapping requestMapping = new RequestMapping();
requestMapping.setMethods(method);
requestMapping.setConsumes(MediaType.MULTIPART_FORM_DATA_VALUE);
requestMapping.setProduces(MediaType.APPLICATION_JSON_VALUE);
requestMapping.setPathPatterns(path);
return requestMapping;
}
@Bean
public IntegrationFlow httpPostFileUpload() {
return IntegrationFlows.from(httpPostGateFileUpload())
.channel("http.file.upload.channel").handle("fileEndpoint", "upload").get();
}
@Bean
public MessagingGatewaySupport httpPostGateFileUpload() {
// @RequestMapping
HttpRequestHandlingMessagingGateway handler = new HttpRequestHandlingMessagingGateway();
handler.setRequestMapping(createMappingFile(new HttpMethod[]{HttpMethod.POST}, "/api/file/upload"));
handler.setStatusCodeExpression(fileParser().parseExpression("T(org.springframework.http.HttpStatus).BAD_REQUEST"));
handler.setRequestPayloadType(ResolvableType.forClass(MultipartFile.class));
handler.setHeaderMapper(fileHeaderMapper());
return handler;
}
FileEndpoint:
public Message<?> upload(Message<MultipartFile>msg) {
MultipartFile file = msg.getPayload();
UserDetails loggedUser = (UserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
Optional<User> opUser = userRepository.findByUsername(loggedUser.getUsername());
User user = opUser.orElseThrow(()->new ResponseStatusException(HttpStatus.NOT_FOUND,"User not found"));
long date = new Date().getTime();
File convertFile = new File(resourcePath+date+"_"+file.getOriginalFilename());
try {
FileOutputStream fout = new FileOutputStream(convertFile);
fout.write(file.getBytes());
fout.close();
...
我将文件推送到目录中。 例外:
org.springframework.messaging.MessagingException: Could not convert request: no suitable HttpMessageConverter found for expected type [org.springframework.web.multipart.MultipartFile] and content type [multipart/form-data;boundary=--------------------------525212308988156732836650;charset=UTF-8]
at org.springframework.integration.http.inbound.HttpRequestHandlingEndpointSupport.extractRequestBody(HttpRequestHandlingEndpointSupport.java:513) ~[spring-integration-http-5.1.6.RELEASE.jar:5.1.6.RELEASE]
```
答案 0 :(得分:0)
请阅读有关此事的Reference Manual:
如果一个bean名称为
MultipartResolver
(与Spring的multipartResolver
相同,则HTTP入站端点在上下文中定位一个DispatcherServlet
。如果确实找到该bean,则在入站请求映射器上启用对多部分文件的支持。否则,当尝试将多部分文件请求映射到Spring Integration Message时,它将失败。有关Spring对MultipartResolver
的支持的更多信息,请参见Spring参考手册。
还有一个有关multipart support的示例。