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);
	}

Using @RequestPart

	/**
	 * 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);
	}

Frontend Code

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!");
});;



Subscribe To Our Newsletter
You will receive our latest post and tutorial.
Thank you for subscribing!

required
required


Leave a Reply

Your email address will not be published. Required fields are marked *