【问题标题】:Angular 5 + Spring boot image uploadAngular 5 + Spring boot 图像上传
【发布时间】:2018-04-06 10:56:05
【问题描述】:

我正在尝试将图像从 Angular 上传到 Spring Boot Rest。但它会抛出

org.springframework.web.multipart.MultipartException: Current request is not a multipart request
    at org.springframework.web.method.annotation.RequestParamMethodArgumentResolver.handleMissingValue(RequestParamMethodArgumentResolver.java:190) ~[spring-web-4.3.13.RELEASE.jar:4.3.13.RELEASE]

我对这两种技术都很陌生。帮我上传文件。

这里是代码。

RestController

public ResponseMessage addUser(@RequestParam("profileImage") MultipartFile profileImage,
    @RequestParam("user") User user) {

try {
    if (userService.doesUserExist(user.getUsername())) {
    return new ResponseMessage("The username is not available; please choose a different username", 200);
    }
} catch (Exception e) {
    System.out.println(e.getMessage());
}
String extension = FilenameUtils.getExtension(profileImage.getOriginalFilename());
storageService.storeFile(profileImage, user.getUsername() + "." + extension, profilePicturePath);
user.setProfilePicturePath(profilePicturePath + "/" + user.getUsername() + "." + extension);
userService.addUser(user);

return new ResponseMessage(user.getUsername() + " was added successfully!", 200);
}

角度服务

addUser(user:User,profileImage:File){
      const formData:FormData = new FormData();

     formData.append('profileImage', profileImage);
     formData.append('user',JSON.parse(JSON.stringify(user)));

     return this.http.post<ResponseMessage>("/api/admin/user/new_user",formData,this.postHttpOptions);

    }

角度组件

setImage(files:FileList){
    this.newProfileImage = files.item(0);
  }
upload(){
if (this.newUser.password == this.newUser.confirmPassword) {
      this.userService.addUser(this.newUser,this.newProfileImage).subscribe(
        res => {
          this.responseMessage = res;
          alert(this.responseMessage.message);
        },
        err => {
          alert("Error Adding the user: " + err.message);
        }
      );
    }
}

角度模板

<input type='file' id="imgInp" (change)="setImage($event.target.files)" />

【问题讨论】:

  • 请分享完整的堆栈跟踪,以及从角度请求的curl

标签: java typescript spring-boot angular5


【解决方案1】:

我明白了。

我所做的更改..

  1. 我添加了@Requestpart 而不是@RequestParam
  2. 我添加了@RequestPart String 用户,而不是@RequestParam User 用户;然后使用 ObjectMapper 将字符串转换为用户。
  3. 在客户端,我删除了'ContentType = application/Json',并没有提到任何内容类型

这里是代码

public String addUser(@RequestPart("profileImage") MultipartFile profileImage,
        @RequestPart("user") String userString) throws JsonParseException, JsonMappingException, IOException {

    User user = new ObjectMapper().readValue(userString, User.class);
}

【讨论】:

    猜你喜欢
    • 2019-09-23
    • 1970-01-01
    • 1970-01-01
    • 2019-07-07
    • 2017-12-30
    • 2017-01-20
    • 2018-10-30
    • 1970-01-01
    • 2021-04-27
    相关资源
    最近更新 更多