根据文件地址获取文件,然后转成Base64位编码字符串
前言
利用文件下载地址获取到文件后,再转成Base64位编码。
一、代码
1.Base64编码
/**
* 根据文件url获取文件并转换为base64编码
*
* @param srcUrl 文件地址
* @param requestMethod 请求方式("GET","POST")
* @return 文件base64编码
*/
public static String netSourceToBase64(String srcUrl,String requestMethod) {
ByteArrayOutputStream outPut = new ByteArrayOutputStream();
byte[] data = new byte[1024 * 8];
try {
// 创建URL
URL url = new URL(srcUrl);
// 创建链接
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod(requestMethod);
conn.setConnectTimeout(10 * 1000);
if (conn.getResponseCode() != HttpURLConnection.HTTP_OK) {
//连接失败/链接失效/文件不存在
return null;
}
InputStream inStream = conn.getInputStream();
int len = -1;
while (-1 != (len = inStream.read(data))) {
outPut.write(data, 0, len);
}
inStream.close();
} catch (IOException e) {
e.printStackTrace();
}
// 对字节数组Base64编码
BASE64Encoder encoder = new BASE64Encoder();
return encoder.encode(outPut.toByteArray());
}
2.解码
代码如下(示例):
/**
* base64 解析
* @param base64Code
* @param targetPath
*/
public static void decodeBase64File(String base64Code, String targetPath) {
// 输出流
FileOutputStream out =null;
// 将base 64 转为字节数字
byte[] buffer = new byte[0];
try {
buffer = new BASE64Decoder().decodeBuffer(base64Code);
// 创建输出流
out = new FileOutputStream(targetPath);
// 输出
out.write(buffer);
} catch (Exception e) {
e.printStackTrace();
}finally {
try {
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
---
# 总结
不断学习,提升自己。