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
spring.servlet.multipart.enabled=true
# Threshold after which files are written to disk.
spring.servlet.multipart.file-size-threshold=2KB
# Max file size.
spring.servlet.multipart.max-file-size=500KB
# Max Request Size
spring.servlet.multipart.max-request-size=100KB

# All files uploaded through the REST API will be stored in this directory
file.upload-dir=upload-dir

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)
				.append("/").append(fileName);
		return builder.toString();
	}

ServiceImpl

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;

@Service
public class FileServiceImpl implements FileService{
	
	@Value("${file.upload-dir}")
	private String uploadDir;
	
	private Path fileStorageLocation;

	@PostConstruct
	private void initInstance() throws Exception {
		this.fileStorageLocation = Paths.get(uploadDir).toAbsolutePath().normalize();
		try {
			Files.createDirectories(this.fileStorageLocation);
		} 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();
		if(!folder.exists())
			folder.mkdirs();
	}

	@Override
	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);
			ensureFolder(uploadFilePath);
			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()) {
				targetFile.delete();
			}
			
			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