1.方法调用 本地路径或http路径
java
public static String fileToBase64(String filePath) throws IOException {
// 判断是否为URL
if (filePath.startsWith("http://") || filePath.startsWith("https://")) {
byte[] bytes = downloadFileToByteArray(filePath);
return Base64.getEncoder().encodeToString(bytes);
} else {
// 处理本地文件
File file = new File(filePath);
try (FileInputStream fileInputStream = new FileInputStream(file)) {
byte[] bytes = new byte[(int) file.length()];
fileInputStream.read(bytes);
return Base64.getEncoder().encodeToString(bytes);
}
}
}
2.请求http连接文件资源获取并存入缓存
java
public static byte[] downloadFileToByteArray(String fileUrl) throws IOException {
// 创建 URL 对象
URL url = new URL(fileUrl);
// 打开 HTTP 连接
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
// 设置请求方法为 GET
connection.setRequestMethod("GET");
// 获取输入流
BufferedInputStream in = new BufferedInputStream(connection.getInputStream());
// 创建字节数组输出流,用于存储从输入流读取的数据
ByteArrayOutputStream out = new ByteArrayOutputStream();
// 定义缓冲区
byte[] buffer = new byte[1024];
int bytesRead;
// 从输入流读取数据到缓冲区,并将缓冲区的数据写入输出流
while ((bytesRead = in.read(buffer)) != -1) {
out.write(buffer, 0, bytesRead);
}
// 关闭输入流和输出流
in.close();
out.close();
// 断开 HTTP 连接
connection.disconnect();
// 将字节数组输出流中的数据转换为字节数组并返回
return out.toByteArray();
}