POST请求在Spring Boot中上传多部分文件

时间:2015-11-20 04:20:54

标签: spring multipart postman

我使用spring boot,我需要上传一个多部分文件(jpg或png文件)。我需要发送一个(POST请求上传多部分文件使用" postman"),任何人都可以提供" postman"如何设置它或告诉我?感谢。

方法:



git rebase -f --onto m' m2 m




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

我的配置类:



@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);
	}
&#13;
&#13;
&#13;

3 个答案:

答案 0 :(得分:3)

邮递员的错误说

  

必需的MultipartFile参数'file'不存在

方法签名看起来很好定义file参数:

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

问题是,在使用邮递员时,您使用dog1作为此参数的名称。将其更改为file以匹配多部分文件的预期参数名称。

答案 1 :(得分:0)

这种方法对我有用。

&#13;
&#13;
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.
&#13;
&#13;
&#13;

答案 2 :(得分:0)

@Override
public Response uploadImage(String token, MultipartFile file) {


    long id=tokenUtil.decodeToken(token);
    Optional<User> user=userRepo.findById(id);
    if(!user.isPresent()) {
        throw new UserException(-5, "User does not exists");

    }
    UUID uuid=UUID.randomUUID();
    String uniqueUserId=uuid.toString();
    try {

        Files.copy(file.getInputStream(), fileLocation.resolve(uniqueUserId), StandardCopyOption.REPLACE_EXISTING);
        user.get().setProfilePic(uniqueUserId);
        userRepo.save(user.get());
    }catch (IOException e) {
        e.printStackTrace();
        // TODO: handle exception
    }
    return ResponseHelper.statusResponse(200, "Profile Pic Uploaded Successfully");


}