Upload File in Spring Boot

In this blog, You can find the sample code for upload file in spring boot. spring boot mostly used to delevelop the rest service. it handles the JSON request and produce the JSON response. So we need to put some extra effort to handle the multipart request for file upload.

The given sample code will be get the MultipartFile from request and store it in our system folder as a file.

First. Add the below properties in application.properties

# Enable multipart uploads
# Threshold after which files are written to disk.
# Max file size.
# Max Request Size

# All files uploaded through the REST API will be stored in this directory

Then you have to add the seprate controller, and service and service implementation classes to handle upload request

@PostMapping(value = "/upload/{category}")
	public String uploadAadhaarID(@RequestParam("file") MultipartFile file, @PathVariable("category") String category,
			@RequestParam("id") Long id) throws Exception {
		String fileName = fileService.storeFile(file, category, id);
		StringBuilder builder = new StringBuilder("/api/secured/file/get/").append(id).append("/").append(category)
		return builder.toString();


package com.samplecoder.demo.service.impl;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.MalformedURLException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;

import javax.annotation.PostConstruct;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.Resource;
import org.springframework.core.io.UrlResource;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import com.samplecoder.demo.service.FileService;

public class FileServiceImpl implements FileService{
	private String uploadDir;
	private Path fileStorageLocation;

	private void initInstance() throws Exception {
		this.fileStorageLocation = Paths.get(uploadDir).toAbsolutePath().normalize();
		try {
		} catch (Exception ex) {
			throw new Exception("Could not create the directory where the uploaded files will be stored.", ex);

	private void ensureFolder(String path) {
		File folder = fileStorageLocation.resolve(path).toFile();

	public String storeFile(MultipartFile file, String category, Long id) throws Exception {
		String fileName = StringUtils.cleanPath(file.getOriginalFilename());
		String uploadFilePath = ""; 
		try {
			// Check if the file's name contains invalid characters
			if (fileName.contains("..")) {
				throw new Exception("Sorry! Filename contains invalid path sequence " + fileName);
			uploadFilePath = String.valueOf(id).concat("/").concat(category);
			uploadFilePath += "/";
			String rename = fileName.replaceAll(" ", "");

			// Copy file to the target location (Replacing existing file with the same name)
			Path targetLocation = this.fileStorageLocation.resolve(uploadFilePath+rename);
			File targetFile = targetLocation.toFile();
			if(targetFile.exists() && targetFile.isFile()) {
			Files.copy(file.getInputStream(), targetLocation, StandardCopyOption.REPLACE_EXISTING);
			return rename;
		} catch (IOException ex) {
			throw new Exception("Could not store file " + fileName + ". Please try again!", ex);
Upload File in Spring Boot