Base64编码中的 64表示的为 0-16 A-Z a-z 和+ / 一共64个字符。
将数据转为二进制数、再将六位作为一组转为十进制数、对应64个字符中进行拼接
1.将文件转为base64编码字符串
public class TestBase64 {
public static void main(String[] args) throws Exception {
// 读取文件字节数组
InputStream in = new FileInputStream("C:\\Users\\Administrator\\Desktop\\扩展系统字典.png");
byte[] data = new byte[in.available()];
in.read(data);
in.close();
// 对字节数组Base64编码
BASE64Encoder encoder = new BASE64Encoder();
// 返回 Base64 编码过的字节数组字符串
String base64Str = encoder.encode(data);
System.out.println(base64Str);
}
}
2.将base64字符串转为文件
public static void main(String[] args) throws Exception {
BASE64Decoder decoder = new BASE64Decoder();
// Base64解码,对字节数组字符串进行Base64解码并生成文件
byte[] byt = decoder.decodeBuffer(str);
for (int i = 0, len = byt.length; i < len; ++i) {
// 调整异常数据
if (byt[i] < 0) {
byt[i] += 256;
}
}
InputStream input = new ByteArrayInputStream(byt);
// 生成指定格式的文件
OutputStream out = new FileOutputStream("C:\\Users\\Administrator\\Desktop\\扩展系统字典1.png");
byte[] buff = new byte[1024];
int len = 0;
while ((len = input.read(buff)) != -1) {
out.write(buff, 0, len);
}
out.flush();
out.close();
}
3.将base64字符串转为MultipartFile文件
3.1 字节转换文件工具类
public class Base64File implements MultipartFile {
private final byte[] imgContent;
private final String header;
private String fileName;
public Base64File(byte[] imgContent, String header,String fileName) {
this.imgContent = imgContent;
this.header = header.split(";")[0];
this.fileName = fileName;
}
@Override
public String getName() {
return System.currentTimeMillis() + Math.random() + "." + header.split("/")[1];
}
@Override
public String getOriginalFilename() {
if (StringUtils.isNoneBlank(fileName)){
return fileName;
}
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);
}
public String getFileName() {
return fileName;
}
public void setFileName(String fileName) {
this.fileName = fileName;
}
public static MultipartFile base64ToMultipart(String base64,String fileName) {
try {
String[] baseStrs = base64.split(",");
BASE64Decoder decoder = new BASE64Decoder();
byte[] b = new byte[0];
b = decoder.decodeBuffer(baseStrs[1]);
for (int i = 0; i < b.length; ++i) {
if (b[i] < 0) {
b[i] += 256;
}
}
return new Base64File(b, baseStrs[0],fileName);
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
}
3.2 调用文件转换
MultipartFile file = Base64File.base64ToMultipart((String)datasMap.get("reportFile"),"自定义文件名");