Reputation: 759
I am trying to upload an image from angular to spring boot rest. but it throws
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]
I am new to both the technologies. Help me upload the file.
Here is the code.
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);
}
Angular Service
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);
}
Angular Component
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);
}
);
}
}
Angular Template
<input type='file' id="imgInp" (change)="setImage($event.target.files)" />
Upvotes: 1
Views: 3832
Reputation: 759
I got it.
The changes I made..
Here is the code
public String addUser(@RequestPart("profileImage") MultipartFile profileImage,
@RequestPart("user") String userString) throws JsonParseException, JsonMappingException, IOException {
User user = new ObjectMapper().readValue(userString, User.class);
}
Upvotes: 1