2015-11-20 121 views
2

我使用的是spring boot,我需要上傳多部分文件(jpg或png文件)。我需要發送(POST請求上傳使用「郵遞員」的多部分文件),任何人都可以提供一個「郵遞員」的屏幕截圖如何設置它來做到這一點或告訴我?謝謝。POST請求在Spring Boot中上傳多部分文件

方法:

@RequestMapping(method = RequestMethod.POST, value = "/upload") 
 
\t @ResponseBody 
 
\t ResponseEntity<?> writeUserProfilePhoto(@PathVariable Long user, @RequestPart("file") MultipartFile file) throws Throwable { 
 
\t \t 
 
\t \t byte bytesForProfilePhoto[] = FileCopyUtils.copyToByteArray(file.getInputStream()); //Return an InputStream to read the contents of the file from. 
 
\t \t 
 
\t \t this.crmService.writeUserProfilePhoto(user, MediaType.parseMediaType(file.getContentType()),bytesForProfilePhoto); 
 
\t \t 
 
\t \t HttpHeaders httpHeaders = new HttpHeaders(); 
 
\t \t 
 
\t \t URI uriOfPhoto = ServletUriComponentsBuilder.fromCurrentContextPath() 
 
\t \t \t \t .pathSegment(("/users" + "/{user}" + "/photo").substring(1)) 
 
\t \t \t \t .buildAndExpand(Collections.singletonMap("user", user)).toUri(); 
 
\t \t 
 
\t \t httpHeaders.setLocation(uriOfPhoto); 
 
\t \t return new ResponseEntity<>(httpHeaders, HttpStatus.CREATED); 
 
\t }

,這是我如何發送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 { 
 

 
\t @Autowired 
 
\t private MultipartProperties multipartProperties = new MultipartProperties(); 
 

 
\t @Bean 
 
\t @ConditionalOnMissingBean 
 
\t public MultipartConfigElement multipartConfigElement() { 
 
\t \t return this.multipartProperties.createMultipartConfig(); 
 
\t } 
 

 
\t @Bean(name = DispatcherServlet.MULTIPART_RESOLVER_BEAN_NAME) 
 
\t @ConditionalOnMissingBean(MultipartResolver.class) 
 
\t public StandardServletMultipartResolver multipartResolver() { 
 
\t \t return new StandardServletMultipartResolver(); 
 
\t } 
 

 
}

+0

參見郵遞員[文檔](https://www.getpostman.com/docs/requests)。 – nobeh

+0

不是[標籤:java]的問題。更多關於如何使用工具的問題。 – nobeh

+0

謝謝我會檢查它:) –

回答

3

在郵遞員的錯誤說

必需MultipartFile參數 '文件' 不存在

方法簽名看起來很好定義file參數:

ResponseEntity<?> writeUserProfilePhoto(
    @PathVariable Long user, @RequestPart("file") MultipartFile file) 
    throws Throwable 

的問題是當使用郵差時,您使用dog1作爲此參數的名稱。將其更改爲file以匹配多部分文件的預期參數名稱。

+0

它的工作。非常感謝。我花時間去尋找那個,你幫了很多忙:) –

0

這種方法適用於我。

The error in postman says 
 

 
Required MultipartFile parameter 'file' is not present 
 
The method signature looks fine defining file parameter: 
 

 
ResponseEntity<?> writeUserProfilePhoto(
 
    @PathVariable Long user, @RequestPart("file") MultipartFile file) 
 
    throws Throwable 
 
The issue is that when using postman, you're using dog1 as the name of this parameter. Change it to file to match the expected parameter name for the multipart file.

相關問題