前臺將圖片以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);
}
}