Search code examples
spring-bootbase64thymeleafmybatismultipartfile

How to insert MultipartFile photo into DB as Base64 String in Java Spring boot and display it on the main screen back from the db


How to insert MultipartFile photo into DB as Base64 String in Java Spring boot and display it on the main screen back from the db.


Solution

  • How to save image to mySQL database with thymeleaf and spring boot

    To save an image to the mySQL database you need to do as following:

    1 - On the bean class, you should declare 3 variables like that:

    @Data
    public class Product implements Serializable{
    
        private byte[] ProductImg;
        
        private MultipartFile UploadFile;
        
        private String Base64Img;
    

    Explanation :

    ProductImg

    is in Byte which is the variable that will store our image to save it to the DB.

    UploadFile

    is the file that you will upload which is the image in our case.

    Base64Img

    is the encoded image after we convert it. Don't worry, I will explain that in details in a moment.

    2- Let's go get the Image:

    First you have to request the image from the HTML file with thymeleaf like that:

    <input type="file" name="image" accept="image/png, image/jpeg"/>
    

    or whatever you prefer.

    3- Let's do our homework in the controller side:

    import org.apache.tomcat.util.codec.binary.Base64;
    
    @RequestMapping(value="/product-registration", method = RequestMethod.POST)
    public String insertProductInfo(@ModelAttribute Product productInfo, @RequestParam(value="image",required=false) MultipartFile file,Model model) {
        productInfo.setUploadFile(file);
        try{
            byte[] image = Base64.encodeBase64(productInfo.getUploadFile().getBytes());
            String result = new String(image);
            System.out.println(result);
            productInfo.setProductImg(image);
        } catch(Exception e) {
            e.printStackTrace();
        }
    
        productService.insert(productInfo);
        return "redirect:/product-list";
    }
    

    So what does this code do is :

    @ModelAttribute Product productInfo productInfo is the model attribute I'm collecting other data with, image is not included, you can include it though.

    @RequestParam(value="image",required=false) MultipartFile file Here I'm getting the image I just uploaded and assigned it to "file" name.

    the rest of the code is converting it to byte and then assign the byte values to the byte variable in Product class after converting it to string. make sure to print what you are inserting to DB, If the file is .png, It should look like that:

    iVBORw0KGgoAAAANSUhEUgAAASwAAAEsCAMAAABOo35HAAAABGdBTUEAALGPC/xhBQAAAAFzUkdCAK7OHOkAAAAgY0hSTQAAeiYAAICEAAD6AAAAgOgAAHUwAADqYAAAOpgAABdwnLpRPAAAADZQ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+nxlq0Q0fyTa/bK4NDvWLryRUV05HMxpYlkmfbTluWj3yppPVW25BDd6tA2ZSY5lyUk2yxTtNllahsMLBzb0E4eDrWqQVc1cZYp2j6zGdOew5u+O63d3se9agfTbi9fvaPZkONPcJYuvjQciMn+LLMoQ0doI4VGWf3+2/5lXbs8b7WJZTbpFnpb2glSiVZS+4CAYGwbdlIoxJsJytGSFwJejUXOxLJlohw+t+Fhja6FSacfLybH30St2Kpr9XBUwpkWbqi+8vE6WVj6RPXdMMvFEnvatTiZAo9sS0fqVpcKyEotRB+Z4xXxprE2UtHU7j3bgwqrEQtwFsqZD4pCppSvYUC/li/YajAVlTRejzMkgYlftcT7afCGumCwepmkmwxxNu7F7FYkWeClZ8X3JNxfe0GdVlG3eT1A8NgrJKqNqfgF3RCsoi7JPmq7puiJaMVlUYn55Udc10QrJ8pIVQn4otktGKyNLaVYMraauLotWQhZxVpQqGh1UlY3GqaAs27LiDK83l0bLuOnlmm4V3+5ro2UMJkv9d7l0tEBE7VXR1GSrRYYb0Lac/Si/fG0AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAADAM/gHzOz/zZvHz10AAAAldEVYdGRhdGU6Y3JlYXRlADIwMjAtMTAtMDNUMjM6MTg6NDYrMDk6MDBUXKpbAAAAJXRFWHRkYXRlOm1vZGlmeQAyMDIwLTEwLTAzVDIzOjE4OjQ2KzA5OjAwJQES5wAAABl0RVh0U29mdHdhcmUAQWRvYmUgSW1hZ2VSZWFkeXHJZTwAAAAASUVORK5CYII=

    4- Insert the image to the db

    I think this step is not a big deal, it's just like inserting any other data Calling the service class and assign the product class variable to it and then insert it to the DB.

    How to pull out the photo from the DB and show it on the screen:

    This part is a little bit tricky, so give me your attention

    1- Controller side:

    String encoded64 = new String(product.getProductImg()); product.setBase64Img(encoded64);

    You will get the encoded image and then assign it to String Base64Img which we have declared in Product class, remember? Until now, you are fine. If you tried to print the encoded64 it will give you the same strange characters I wrote above.

    So what's next?

    2- thymeleaf side

    the code for the image to display on your screen is as follows:

    <img th:src="|data:image;base64,*{Base64Img}|" class="product-image">
    

    *{Base64Img} is the same as ${product.Base64Img} It's inside a form, so ...