我正在使用 Spring Boot,我需要上传多部分文件(jpg 或 png 文件)。我需要发送一个(使用“ postman ”上传多部分文件的 POST 请求),任何人都可以提供“ postman ”的屏幕截图,说明如何设置它或告诉我吗?谢谢。
方法:
@RequestMapping(method = RequestMethod.POST, value = "/upload")
@ResponseBody
ResponseEntity<?> writeUserProfilePhoto(@PathVariable Long user, @RequestPart("file") MultipartFile file) throws Throwable {
byte bytesForProfilePhoto[] = FileCopyUtils.copyToByteArray(file.getInputStream()); //Return an InputStream to read the contents of the file from.
this.crmService.writeUserProfilePhoto(user, MediaType.parseMediaType(file.getContentType()),bytesForProfilePhoto);
HttpHeaders httpHeaders = new HttpHeaders();
URI uriOfPhoto = ServletUriComponentsBuilder.fromCurrentContextPath()
.pathSegment(("/users" + "/{user}" + "/photo").substring(1))
.buildAndExpand(Collections.singletonMap("user", user)).toUri();
httpHeaders.setLocation(uriOfPhoto);
return new ResponseEntity<>(httpHeaders, HttpStatus.CREATED);
}
我的配置类:
@Configuration
@ConditionalOnClass({ Servlet.class, StandardServletMultipartResolver.class, MultipartConfigElement.class })
@ConditionalOnProperty(prefix = "multipart", name = "enabled", matchIfMissing = true)
@EnableConfigurationProperties(MultipartProperties.class)
public class MultipartAutoConfiguration {
@Autowired
private MultipartProperties multipartProperties = new MultipartProperties();
@Bean
@ConditionalOnMissingBean
public MultipartConfigElement multipartConfigElement() {
return this.multipartProperties.createMultipartConfig();
}
@Bean(name = DispatcherServlet.MULTIPART_RESOLVER_BEAN_NAME)
@ConditionalOnMissingBean(MultipartResolver.class)
public StandardServletMultipartResolver multipartResolver() {
return new StandardServletMultipartResolver();
}
}
最佳答案
postman 中的错误说
Required MultipartFile parameter 'file' is not present
方法签名看起来很好定义file
参数:
ResponseEntity<?> writeUserProfilePhoto(
@PathVariable Long user, @RequestPart("file") MultipartFile file)
throws Throwable
问题是,在使用 postman 时,您使用 dog1
作为此参数的名称。将其更改为 file
以匹配多部分文件的预期参数名称。
关于spring - Spring Boot 中上传多部分文件的 POST 请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33818937/