spring - Spring Boot 中上传多部分文件的 POST 请求

标签 spring multipart postman

我正在使用 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);
	}

这就是我发送 POST 请求的方式:enter image description here

我的配置类:

@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/

相关文章:

java - 我可以使用 UrlEncodedFormEntity 为多个部分上传图像和文本吗?

json - 如何在 flutter 中发送多部分请求中的对象列表?

node.js - export.create 和 router.post 有什么区别?

api - POSTMAN - 测试失败为真

node.js - 使用signedURL将base64文件上传到GCS

java - 如何在 Spring Boot 中将 2 个不同 jar 中的 2 个微服务部署到同一端口

java - hibernate 无法重新连接到 mysql 数据库

java - 具有特定父类的切入点匹配类型

java - 获取字符串形式的 MimeMessage 内容

java - spring中indexcontroller和viewresolver的区别