如何从文件下载链接(url)中获取到文件的base64字符串
整体思路:
1.获取到url中的文件流;
2.文件流写入byte[];
3.字节数组转base64;
(不要想着曲线救国,先把文件下载下来再转base64,浪费资源)
代码实现:
public static String downloadFileByUrl(String url) throws IOException {
try {
URL httpurl = new URL(url);
HttpURLConnection connection = (HttpURLConnection) httpurl.openConnection();
connection.connect();
connection.getInputStream();
InputStream is = connection.getInputStream();
ByteArrayOutputStream outStream = new ByteArrayOutputStream();
//创建一个Buffer字符串
byte[] buffer = new byte[1024];
//每次读取的字符串长度,如果为-1,代表全部读取完毕
int len = 0;
while( (len=is.read(buffer)) != -1 ){
outStream.write(buffer, 0, len);
}
//对字节数组Base64编码
BASE64Encoder encoder = new BASE64Encoder();
return encoder.encodeBuffer(outStream.toByteArray());
} catch (Exception e) {
throw e;
}
}
搞定收工!
要是没转成功,那一定是url有问题;