如何將base64格式的圖片字符串轉(zhuǎn)換成MultipartFile

前臺將圖片以base64編碼的字符串傳給后臺,后臺接收后需要轉(zhuǎn)換成MultipartFile,上傳到服務(wù)器上。

網(wǎng)上大部分解決方案使用到了sun.misc.BASE64Encoder進行轉(zhuǎn)換,從 java 8 開始,就用 java.util.Base64 工具類來替換 sun.misc.BASE64Encoder 了。

而我們項目使用的是jdk11,我這邊使用了org.apache.commons.codec.binary.Base64。

修改前
BASE64Decoder decoder = new BASE64Decoder();
byte[] b = new byte[0];
b = decoder.decodeBuffer(baseStrs[1]);

修改后
byte[] b = Base64.decodeBase64(baseStrs[1]);

創(chuàng)建兩個java文件:ImageUtils、Base64DecodeMultipartFile

ImageUtils.base64ToMultipartFile("base64字符串")
import org.apache.commons.codec.binary.Base64;
import org.springframework.web.multipart.MultipartFile;

public class ImageUtils {
    public static MultipartFile base64ToMultipartFile(String base64) {
        //base64編碼后的圖片有頭信息所以要分離出來 [0]data:image/png;base64, 圖片內(nèi)容為索引[1]
        String[] baseStrs = base64.split(",");

        //取索引為1的元素進行處理
        byte[] b = Base64.decodeBase64(baseStrs[1]);
        for (int i = 0; i < b.length; ++i) {
            if (b[i] < 0) {
                b[i] += 256;
            }
        }

        //處理過后的數(shù)據(jù)通過Base64DecodeMultipartFile轉(zhuǎn)換為MultipartFile對象
        return new Base64DecodeMultipartFile(b, baseStrs[0]);
    }
}
import org.springframework.web.multipart.MultipartFile;
import java.io.*;

public class Base64DecodeMultipartFile implements MultipartFile {
    private final byte[] imgContent;
    private final String header;

    public Base64DecodeMultipartFile(byte[] imgContent, String header) {
        this.imgContent = imgContent;
        this.header = header.split(";")[0];
    }

    @Override
    public String getName() {
        return System.currentTimeMillis() + Math.random() + "." + header.split("/")[1];
    }

    @Override
    public String getOriginalFilename() {
        return System.currentTimeMillis() + (int) Math.random() * 10000 + "." + header.split("/")[1];
    }

    @Override
    public String getContentType() {
        return header.split(":")[1];
    }

    @Override
    public boolean isEmpty() {
        return imgContent == null || imgContent.length == 0;
    }

    @Override
    public long getSize() {
        return imgContent.length;
    }

    @Override
    public byte[] getBytes() throws IOException {
        return imgContent;
    }

    @Override
    public InputStream getInputStream() throws IOException {
        return new ByteArrayInputStream(imgContent);
    }

    @Override
    public void transferTo(File dest) throws IOException, IllegalStateException {
        new FileOutputStream(dest).write(imgContent);
    }
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容