I need to upload a photo to the server which has been written using Spring Boot. For the front end which sends the request I use Angular2.
This is my API which accepts the HTTP request. It works fine. (I tested it using Postman)
@RequestMapping(method = RequestMethod.POST, value = "/tender/save-new/save-photo")
public ResponseEntity<?> uploadPhoto(@RequestParam("file") MultipartFile file){
if (file.isEmpty()) {
ErrorResponse errorResponse = new ErrorResponse();
errorResponse.setMessage("DEBUG: Attached file is empty");
return new ResponseEntity<ErrorResponse>(errorResponse, HttpStatus.NOT_FOUND);
}
String returnPath = null;
try {
// upload stuff
} catch (IOException e) {
ErrorResponse errorResponse = new ErrorResponse();
errorResponse.setMessage(e.getMessage());
return new ResponseEntity<ErrorResponse> (errorResponse, HttpStatus.INTERNAL_SERVER_ERROR);
}
return new ResponseEntity<String>(returnPath, HttpStatus.OK);
}
I am not sure how should I write the code in Angular2 to call the server. Following is what I have come up with.
savePhoto(photoToSave: File) {
let formData: FormData = new FormData();
formData.append('file', photoToSave);
let savedPath = this._http
.post(this._endpointUrl + "tender/save-new/save-photo", formData)
.map(
res => {
return res.json();
}
)
.catch(handleError);
return savedPath;
}
As you can see, I append the 'file'
parameter to the form data before sending it. Server method accepts the RequestParam
as 'file'
.
But, in the server log, I get following error.
org.springframework.web.multipart.MultipartException: Current request is not a multipart request at org.springframework.web.method.annotation.RequestParamMethodArgumentResolver.handleMissingValue(RequestParamMethodArgumentResolver.java:190)
Note that I haven't declared a CommonsMultipartResolver
bean since SprinBoot implicitly handles it. (I have heard this. Please correct if I am wrong.)
I think that the error comes up because of a missing value in the request. What Spring is saying by handleMissingValue
? What am I missing?