MultipartFile转base64
/**
* 将MultipartFile 图片文件编码为base64
* @param file
* @return
* @throws Exception
*/
public static String generateBase64(MultipartFile file){
if (file == null || file.isEmpty()) {
throw new RuntimeException("图片不能为空!");
}
String fileName = file.getOriginalFilename();
String fileType = fileName.substring(fileName.lastIndexOf("."));
String contentType = file.getContentType();
byte[] imageBytes = null;
String base64EncoderImg="";
try {
imageBytes = file.getBytes();
BASE64Encoder base64Encoder =new BASE64Encoder();
/**
* 1.Java使用BASE64Encoder 需要添加图片头("data:" + contentType + ";base64,"),
* 其中contentType是文件的内容格式。
* 2.Java中在使用BASE64Enconder().encode()会出现字符串换行问题,这是因为RFC 822中规定,
* 每72个字符中加一个换行符号,这样会造成在使用base64字符串时出现问题,
* 所以我们在使用时要先用replaceAll("[\\s*\t\n\r]", "")解决换行的问题。
*/
base64EncoderImg = "data:" + contentType + ";base64," + base64Encoder.encode(imageBytes);
base64EncoderImg = base64EncoderImg.replaceAll("[\\s*\t\n\r]", "");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return base64EncoderImg;
}
base64转MultipartFile
思路: 先将base64转成File,再将File转成MultipartFile
base64转File,涉及使用枚举类
/**
* base64文件类型,前缀
* @author
*/
public enum Base64FileTypeEnum {
// 文件类型
BASE64_FILETYPE_DOC(".doc", "data:application/msword;base64"),
BASE64_FILETYPE_DOCX(".docx", "data:application/vnd.openxmlformats-officedocument.wordprocessingml.document;base64"),
BASE64_FILETYPE_XLS(".xls", "data:application/vnd.ms-excel;base64"),
BASE64_FILETYPE_XLSX(".xlsx", "data:application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;base64"),
BASE64_FILETYPE_PDF(".pdf", "data:application/pdf;base64"),
BASE64_FILETYPE_PPT(".ppt", "data:application/vnd.ms-powerpoint;base64"),
BASE64_FILETYPE_PPTX(".pptx", "data:application/vnd.openxmlformats-officedocument.presentationml.presentation;base64"),
BASE64_FILETYPE_TXT(".txt", "data:text/plain;base64"),
// 图片类型
BASE64_FILETYPE_PNG(".png", "data:image/png;base64"),
BASE64_FILETYPE_JPG(".jpg", "data:image/jpeg;base64"),
BASE64_FILETYPE_JPEG(".jpeg", "data:image/jpeg;base64"),
BASE64_FILETYPE_GIF(".gif", "data:image/gif;base64"),
BASE64_FILETYPE_SVG(".svg", "data:image/svg+xml;base64"),
BASE64_FILETYPE_ICO(".ico", "data:image/x-icon;base64"),
BASE64_FILETYPE_BMP(".bmp", "data:image/bmp;base64"),
// // 二进制流
// BASE64_FILETYPE_OCTET_STREAM("octet-stream", "data:application/octet-stream;base64,"),
;
private Base64FileTypeEnum(String code, String value) {
this.code = code;
this.value = value;
}
private String code;
private String value;
public String getCode() {return code;}
public String getValue() {return value;}
public static String getFileType(String value) {
Base64FileTypeEnum[] types = values();
for (Base64FileTypeEnum x : types) {
if (x.getValue().equals(value)) {
return x.getCode();
}
}
return null;
}
}
//BASE64解码成File文件
public File base64ToFile(String base64, String fileName) {
File file = null;
//创建文件目录
String filePath=this.getClass().getClassLoader().getResource("").getPath();
File dir=new File(filePath);
if (!dir.exists() && !dir.isDirectory()) {
dir.mkdirs();
}
BufferedOutputStream bos = null;
FileOutputStream fos = null;
try {
//截取base64头部,获取文件类型
String fileType = Base64FileTypeEnum.getFileType(base64.substring(0, base64.indexOf(",")));
//去掉头部,防止转换文件后打开显示文件损坏
String s = base64.substring(base64.indexOf(",")+1);
byte[] bytes = new BASE64Decoder().decodeBuffer(s);
file=new File(filePath+"/"+fileName+fileType);
fos = new FileOutputStream(file);
bos = new BufferedOutputStream(fos);
bos.write(bytes);
} catch (IOException e) {
e.printStackTrace();
} finally {
if (bos != null) {
try {
bos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (fos != null) {
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return file;
}
生成File后我们转成MultipartFile
//File转MultipartFile
public static MultipartFile getMultipartFile(File file) {
FileItem item = new DiskFileItemFactory().createItem("file"
, MediaType.MULTIPART_FORM_DATA_VALUE
, true
, file.getName());
try (InputStream input = new FileInputStream(file);
OutputStream os = item.getOutputStream()) {
// 流转移
IOUtils.copy(input, os);
} catch (Exception e) {
throw new IllegalArgumentException("Invalid file: " + e, e);
}
return new CommonsMultipartFile(item);
}