Gary' Blog

Java Image base64 to Spring Boot MultipartFile

Java code:

package com.awaimai;

import cn.hutool.core.lang.Assert;
import lombok.extern.slf4j.Slf4j;
import org.apache.tika.mime.MimeTypeException;
import org.apache.tika.mime.MimeTypes;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.web.multipart.MultipartFile;

import java.util.Base64;

@Slf4j
public class ImageUtil {
    public static MultipartFile base64ToMultipartFile(String name, String base64) {
        Assert.notBlank(name);
        Assert.notBlank(base64);
        Assert.isTrue(base64.startsWith("data:image/"));

        int colon = base64.indexOf(":");
        int semicolon = base64.indexOf(";");
        String mimeType = base64.substring(colon + 1, semicolon);
        String base64WithoutHeader = base64.substring(semicolon + 8);

        byte[] bytes = Base64.getDecoder().decode(base64WithoutHeader);

        String extension = ".jpg";
        try {
            extension = MimeTypes.getDefaultMimeTypes().forName(mimeType).getExtension();
        } catch (MimeTypeException e) {
            log.error("Can't get extension from mimeType [{}]", mimeType);
        }
        String filename = name + extension;
        return new MockMultipartFile(filename, filename, mimeType, bytes);
    }
}

Use it:

String AlphabetE = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADYAAABGCAMAAACwuZcuAAAANlBMVEX///8zMzNiYmJFRUVOTk5RUVG/v7+qqqqjo6N0dHTS0tLy8vLd3d3Nzc29vb2vr697e3tsbGzFnY9TAAAAXElEQVRIx+3ROQrAMAxEUcWysq/3v2wgpYWcEAQ2eF47/GoIALycbFkpI3SWufEsDsryIZtIK5Dt/7JYUcZj4njLDMgkESq8G5lXJr2y5TMLt5pdZibPLgQA4OAGVUEF2RhRZuwAAAAASUVORK5CYII=";

MultipartFile multipartFile = ImageUtil.base64ToMultipartFile("AlphabetE", this.AlphabetE);
Assertions.assertEquals("image/png", multipartFile.getContentType());
Exit mobile version