/**
* 文件链接转base64
* @param urlStr 文件在线url
* @return 文件base64格式
*/
public static String fileToBase64(String urlStr){
String base64 = null;
try {
// 统一资源
URL url = new URL(urlStr);
// 连接类的父类,抽象类
URLConnection urlConnection = url.openConnection();
// http的连接类
HttpURLConnection httpURLConnection = (HttpURLConnection) urlConnection;
//设置超时
httpURLConnection.setConnectTimeout(1000 * 5);
//设置请求方式,默认是GET
httpURLConnection.setRequestMethod("POST");
// 设置字符编码
httpURLConnection.setRequestProperty("Charset", "UTF-8");
// 打开到此 URL引用的资源的通信链接(如果尚未建立这样的连接)。
httpURLConnection.connect();
// 文件大小
int fileLength = httpURLConnection.getContentLength();
// 控制台打印文件大小
System.out.println("您要下载的文件大小为:" + fileLength / (1024 * 1024) + "MB");
// 建立链接从请求中获取数据
URLConnection con = url.openConnection();
BufferedInputStream bin = new BufferedInputStream(httpURLConnection.getInputStream());
byte[] buffer = new byte[1024];
//每次读取的字符串长度,如果为-1,代表全部读取完毕
int len;
ByteArrayOutputStream outStream = new ByteArrayOutputStream();
while ((len = bin.read(buffer)) != -1) {
outStream.write(buffer, 0, len);
}
bin.close();
byte[] bytes = outStream.toByteArray();
BASE64Encoder base64Encoder = new BASE64Encoder();
System.out.println("base64" + base64Encoder.encode(bytes));
bin.close();
base64 = base64Encoder.encode(bytes);
} catch (IOException e) {
e.printStackTrace();
}
return base64;
}
08-09
1880
08-24
1138
02-23
336