將base64格式的圖片字符串轉換成MultipartFile


轉自:https://www.jianshu.com/p/d9c16b3ffd3c

byte[] decode = Base64.getDecoder().decode(imgFile);
String img = new String(decode);
log.info("上傳圖片......");
MultipartFile file = ImageUtils.base64ToMultipartFile(img);

創建兩個java文件:ImageUtils、Base64DecodeMultipartFile

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, 圖片內容為索引[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;
            }
        }

        //處理過后的數據通過Base64DecodeMultipartFile轉換為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);
    }
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM