Upload file feature in SpringBoot

Vivek Singh
Nerd For Tech
Published in
3 min readAug 17, 2022

--

In this article, we will implement the file upload feature. We will create two endpoints which will upload and get the files respectively. The post request will upload the file. Post request can also be used as a put request.
The get request will get the file.

GitHub code available . Check ReadMe file to start the application.

Post Endpoint :

@PostMapping("/upload/post")
public ResponseEntity<String> uploadProfilePic(@ModelAttribute User user) throws Exception {
userService.updateProfilePicture(user.getUserId(), user.getProfilePicImageFile());
return new ResponseEntity<>( "Upload Successful", HttpStatus.OK);
}

Get Endpoint :

@GetMapping(value = { "/upload/get" }, produces = MediaType.ALL_VALUE)
public ResponseEntity<byte[]> getProfilePic(@RequestParam String emailId) {
log.debug("Inside {} controller", "/user/profile/picture");
User user = userService.getUserDetailsByEmailId(emailId);
byte[] profilePicBytes = user.getProfilePicBytes();
return new ResponseEntity<>(profilePicBytes, HttpStatus.OK);
}

User Entity :

import org.springframework.web.multipart.MultipartFile;class User {
String userId;
String emailId;
byte[] profilePicBytes;
@Transient
private MultipartFile profilePicImageFile;
}

UserServiceImpl :

@Override
public void updateProfilePicture(String userId, MultipartFile multipartFile) throws Exception {
User user = userRepository.findByUserId(userId);
if(user!= null && multipartFile!=null) {
user.setProfilePicBytes(multipartFile.getBytes());
userRepository.save(user);
} else {
log.debug("User not found for userId : {}", userId);
throw new Exception("User not found for { userId = " + userId + "}");
}
}

How to call these endpoints from postman?

Post request : /users/upload/post

Get request : /users/upload/get

Explanation of code:

In the User entity, we have userId, emailId, profilePicBytes, profilePicImageFile. profilePicImageFile is just used to read the file which is passed while calling the post request. We convert this file to a byte type variable and store this array of bytes in our db.

During get call, we read these array of bytes and pass this to frontend, so that the bytes are converted to image. For the conversion we use :

produces = MediaType.ALL_VALUE

while defining the “/upload/get” controller. If we know the the MediaType produced by our get endpoint, then we can use a specific mediatype. Like :

produces = MediaType.IMAGE_JPEG_VALUE

Bytes Conversion of Image :

MultipartFile object has a method called “getBytes()”. This method is used to convert the file to bytes, which can then be stored in the DB. In the below code we just read the file in bytes, and then set it to profilePicBytes (byte[] type object) column/variable of our User Entity.

user.setProfilePicBytes(multipartFile.getBytes());

@ModelAttribute :

In the post request “/users/upload/post” we are using @ModelAttribute instead of @RequestBody -the @ModelAttribute will take a query string. so, all the data are being passed to the server through the url. As for @RequestBody, all the data will be passed to the server through a full JSON body. Image upload wouldn’t be possible with@RequestBody.

Multipart :

Multipart requests combine one or more sets of data into a single body, separated by boundaries. You typically use these requests for file uploads and for transferring data of several types in a single request (for example, a file along with a JSON object).

Conclusion

Hope this article was helpful.
Git Code available with a readme file for explanation : https://github.com/Viveksingh1313/uploadImage

If this article helped you, drop in a clap and follow me for more such articles.
You can find my LinkedIn profile and email Id : vivek.sinless@gmail.com

Happy learning! Cheers :)

--

--

Vivek Singh
Nerd For Tech

Software Developer. I write about Full Stack, NLP and Blockchain. Buy me a coffee - buymeacoffee.com/viveksinless