Springboot Rest File Upload
Posting a request of a DTO which has a file in it.
/**
* User @ModelAttribute instead of @RequestBody
* @param userCreateDTO
* @return
*/
@ApiOperation(value = "Post file in DTO")
@PostMapping(value="/withdto")
public ResponseEntity<User> postWithDTO(@ApiParam(name = "user", required = true, value = "user") @ModelAttribute UserCreateDTO userCreateDTO){
log.info("postWithDTO(..)");
log.info("name: {}, email: {}",userCreateDTO.getName(),userCreateDTO.getEmail());
log.info("file size:{}, name:{}", userCreateDTO.getFile().getSize(),userCreateDTO.getFile().getOriginalFilename());
return new ResponseEntity<>(userService.create(new User(null,null,userCreateDTO.getName(),userCreateDTO.getEmail(),null)), HttpStatus.OK);
}
/**
* post json object with a file using @RequestPart
*/
@ApiOperation(value = "Post file with RequestPart")
@PostMapping("/withrequestpart")
public ResponseEntity<User> postWithRequestPart(@ApiParam(name = "file", required = true, value = "file") @RequestPart(value = "file", required = true) MultipartFile file, @RequestPart("user") User user){
log.info("postWithRequestPart(..)");
log.info(user.toJson());
log.info("file size:{}, name:{}", file.getSize(),file.getName());
return new ResponseEntity<>(userService.create(user), HttpStatus.OK);
}
var formData = new FormData();
formData.append("file", document.forms["userForm"].file.files[0]);
formData.append('user', new Blob([JSON.stringify({
"firstName": document.getElementById("firstName").value,
"lastName": document.getElementById("lastName").value
})], {
type: "application/json"
}));
fetch('/upload', {
method: 'post',
body: formData
}).then(function (response) {
if (response.status !== 200) {
alert("There was an error!");
} else {
alert("Request successful");
}
}).catch(function (err) {
alert("There was an error!");
});;