Reputation: 33
So I'm making a RESTful API backend for a JavaScript frontend and want to upload a file to Google Cloud Storage. I have this function to handle the file upload:
@RequestMapping(value = "/uploadFile", method = RequestMethod.POST, consumes = { "multipart/form-data" })
public ResponseEntity<?> uploadFile(@ModelAttribute("file") FileDTO fileDTO) {
FunctionResponse uploadResponse = cloudStorage.uploadObject(fileDTO.getFile());
if (uploadResponse.successful()) {
return new ResponseEntity<>(uploadResponse.getMessage(), HttpStatus.OK);
} else {
return new ResponseEntity<>(uploadResponse.getMessage(), HttpStatus.BAD_REQUEST);
}
}
My fileDTO class looks like this:
public class FileDTO implements Serializable {
private MultipartFile file;
public MultipartFile getFile() {
return file;
}
}
However whenever I try and access the MultipartFile it always throws a java.lang.NullPointerException
.
I have tried various SO answers from threads with similar problems but none have worked so far.
I have multipart.enabled=true
in my application.properties.
Any help would be appreciated and let me know if you need any more information.
Upvotes: 0
Views: 2495
Reputation: 3390
When a multipart/form-data
request arrives, the data must be obtained by using @RequestParam
, not @ModelAttribute
+ if the value you need of the request is a file, then, it should be deserialized into a MultipartFile
object.
@RequestMapping(value = "/uploadFile", method = RequestMethod.POST, consumes = {"multipart/form-data"})
public ResponseEntity<?> uploadFile(@RequestParam(name = "file") MultipartFile file) {
// your handle ...
}
Upvotes: 1