package com.by4cloud.platformx.business.utils;
|
|
import java.io.ByteArrayOutputStream;
|
import java.io.InputStream;
|
import java.net.HttpURLConnection;
|
import java.net.URL;
|
import java.util.Base64;
|
|
public class NetworkFileToBase64 {
|
|
/**
|
* 将网络地址的文件转换为 Base64 字符串
|
*
|
* @param fileUrl 网络文件的 URL 地址
|
* @return Base64 编码字符串,失败返回 null
|
*/
|
public static String convertNetworkFileToBase64(String fileUrl) {
|
InputStream inputStream = null;
|
ByteArrayOutputStream outputStream = null;
|
|
try {
|
// 1. 创建 URL 对象
|
URL url = new URL(fileUrl);
|
|
// 2. 打开连接
|
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
|
|
// 3. 设置请求属性和超时时间(防止长时间挂起)
|
conn.setRequestMethod("GET");
|
conn.setConnectTimeout(5000); // 连接超时 5秒
|
conn.setReadTimeout(10000); // 读取超时 10秒
|
|
// 4. 获取输入流
|
int responseCode = conn.getResponseCode();
|
if (responseCode != HttpURLConnection.HTTP_OK) {
|
System.err.println("HTTP 错误代码: " + responseCode);
|
return null;
|
}
|
|
inputStream = conn.getInputStream();
|
outputStream = new ByteArrayOutputStream();
|
|
// 5. 读取数据到内存
|
byte[] buffer = new byte[1024];
|
int len;
|
while ((len = inputStream.read(buffer)) != -1) {
|
outputStream.write(buffer, 0, len);
|
}
|
|
// 6. 获取字节数组并编码
|
byte[] fileBytes = outputStream.toByteArray();
|
return Base64.getEncoder().encodeToString(fileBytes);
|
|
} catch (Exception e) {
|
e.printStackTrace();
|
return null;
|
} finally {
|
// 7. 关闭资源
|
try {
|
if (inputStream != null) inputStream.close();
|
if (outputStream != null) outputStream.close();
|
} catch (Exception e) {
|
e.printStackTrace();
|
}
|
}
|
}
|
|
}
|