Upload Image File as Base64 String in Spring Boot
To upload image files as a String in Spring Boot, the file must first be converted into a Base64 string on the frontend and transfer the resulting value via a REST api. It is also imported to note that the size of the encoded Base64 file is increased by 33% of the original size. Therefore, this method is generally not preferred by most of the developers.
Follow these steps:
- Create a DTO class with two fields as shown in the example below:
- Create a controller to upload an image file as a string:
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;
}
}
If you're going to save the file as a string in a database then you should also save the filename because you'll need it later to convert the base64 value to a file.
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
}
}