java 系列文章
提示:这里可以添加系列文章的所有文章的目录,目录需要自己手动添加
提示:写完文章后,目录可以自动生成,如何生成可参考右边的帮助文档
文章目录
前言
提示:这里可以添加本文要记录的大概内容:
文件转换:
- base64 转 MultipartFile
- MultipartFile 转 base64
以下是具体的代码示例
提示:以下是本篇文章正文内容,下面案例可供参考
一、base64 转 MultipartFile
1. 直接调用 base64Convert 方法
2. 示例代码 (复制过去直接用)
package com.hewa.document.convert;
import org.springframework.web.multipart.MultipartFile;
import sun.misc.BASE64Decoder;
import java.io.*;
/**
* @Description: 文件格式转换
* @Author: bingwoo
*/
public class Base64DecodeMultipartFile implements MultipartFile {
private final byte[] imgContent;
private final String header;
public static MultipartFile base64Convert(String base64) {
String[] baseStrs = base64.split(","); //base64编码后的图片有头信息所以要分离出来 [0]data:image/png;base64, 图片内容为索引[1]
BASE64Decoder decoder = new BASE64Decoder();
byte[] b = new byte[0];
try {
b = decoder.decodeBuffer(baseStrs[1]); //取索引为1的元素进行处理
} catch (IOException e) {
e.printStackTrace();
}
for (int i = 0; i < b.length; ++i) {
if (b[i] < 0) {
b[i] += 256;
}
}
return new Base64DecodeMultipartFile(b, baseStrs[0]);//处理过后的数据通过Base64DecodeMultipartFile转换为MultipartFile对象
}
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);
}
}
二、MultipartFile 转 base64
1. 示例代码
/**
* MultipartFile文件转base64
*/
public static String base64ByMultipartFile(MultipartFile file){
if (file == null || file.isEmpty()) {
throw new RuntimeException("图片不能为空!");
}
byte[] imageBytes = null;
String base64EncoderImg="";
try {
imageBytes = file.getBytes();
base64EncoderImg = Base64.encode(imageBytes);
base64EncoderImg = base64EncoderImg.replaceAll("[\\s*\t\n\r]", "");
} catch (IOException e) {
e.printStackTrace();
}
return base64EncoderImg;
}
总结
提示:这里对文章进行总结:
如果遇到其他文件类型的转换问题,欢迎留言!