Upload Image File as Base64 String in Spring Boot

In most of the modern web applications, we may need to upload images file to server and save them in database as a String value. There are two ways of doing it:

  1. Converting image file to Base64 string at frontend.
  2. Converting image file to Base64 string at server-end.

Here is an example code below, the image file must be converted to Base64 string at frontend:

DTO class

public class ImageDTO {
	private String fileContentBase64;
	private String fileName;

	public String getFileContentBase64() {
		return fileContentBase64;
	}

	public void setFileContentBase64(String fileContentBase64) {
		this.fileContentBase64 = fileContentBase64;
	}

	public String getFileName() {
		return fileName;
	}

	public void setFileName(String fileName) {
		this.fileName = fileName;
	}

}
Controller class

import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.example.uploadfiles.dto.ImageDTO;

@RestController
@RequestMapping(path = "/upload")
public class ImageUploadController {

	@PostMapping(path = "/images")
	public void uploadFile(@RequestBody  ImageDTO imageDTO) {
		// Here you can save image base64 string to database
	}
}

Here is another example code which takes multiple image files as a list of Multipart objects and converts them to Base64 string at server-end:

Controller class

import java.io.IOException;
import java.util.List;
import org.apache.tomcat.util.codec.binary.Base64;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

@RestController
@RequestMapping(path = "/upload")
public class ImageUploadController {

	@PostMapping(path = "/images")
	public void uploadFile(@RequestPart(name = "images", required = true) List<MultipartFile> images) {
		images.forEach(f -> {

			try {
				String fileName = f.getOriginalFilename();
				String fileContentBase64 = Base64.encodeBase64String(f.getBytes());
				// Here you can save fileName and file Content as Base64 string to your database
			} catch (IOException e) {
				e.printStackTrace();
			}

		});
	}
}