gpt4 book ai didi

java - Angular 5 + Spring boot 图片上传

转载 作者:行者123 更新时间:2023-11-30 06:14:15 27 4
gpt4 key购买 nike

我正在尝试将图像从 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)" />

最佳答案

我明白了。

我所做的改变..

  1. 我添加了@Requestpart,而不是@RequestParam
  2. 我添加了@RequestPart String user,而不是@RequestParam User user;然后使用ObjectMapper将String转换为用户。
  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);
}

关于java - Angular 5 + Spring boot 图片上传,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49578927/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com