Java文件与Base64之间的转化
1、文件转Base64工具类
可以将图片、视频转化为Base64格式
/**
* 文件转Base64
* @param filePath
* @return
*/
public static String convertFileToBase64(String filePath) {
try {
// 读取文件为字节数组
byte[] fileBytes = Files.readAllBytes(Paths.get(filePath));
// 将字节数组转换为Base64编码的字符串
String base64EncodedString = Base64.getEncoder().encodeToString(fileBytes);
return base64EncodedString;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
2、Base64转文件工具类
将Base64格式的图片、视频下载到本地
/**
* Base64转文件
* @param base64String Base64字符串
* @param filePath 输出的文件路径
* @param mimeType
* MIME类型:
* 视频 video/mp4
* PNG: image/png
* JPEG: image/jpeg
* GIF: image/gif
* BMP: image/bmp
* WebP: image/webp
* @return
*/
public static boolean convertBase64ToFile(String base64String, String filePath, String mimeType) {
try {
// 将Base64编码的字符串转换为字节数组
byte[] fileBytes = Base64.getDecoder().decode(base64String);
// 创建文件头信息
String header = "data:" + mimeType + ";base64,";
byte[] headerBytes = header.getBytes();
// 合并文件头和文件内容
byte[] combinedBytes = new byte[headerBytes.length + fileBytes.length];
System.arraycopy(headerBytes, 0, combinedBytes, 0, headerBytes.length);
System.arraycopy(fileBytes, 0, combinedBytes, headerBytes.length, fileBytes.length);
// 将字节数组写入文件
Files.write(Paths.get(filePath), fileBytes);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
3、综合案例
package org.ming;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.*;
public class FileToBase64Converter {
/**
* 文件转Base64
* @param filePath
* @return
*/
public static String convertFileToBase64(String filePath) {
try {
// 读取文件为字节数组
byte[] fileBytes = Files.readAllBytes(Paths.get(filePath));
// 将字节数组转换为Base64编码的字符串
String base64EncodedString = Base64.getEncoder().encodeToString(fileBytes);
return base64EncodedString;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
/**
* 文件转Base64流程
*/
public static List
总结
以上为个人经验,希望能给大家一个参考,也希望大家多多支持IT俱乐部。