public String convertFileToBase64(String imgPath) {
byte[] data = null;
// 读取图片字节数组
ByteArrayOutputStream out = new ByteArrayOutputStream();
//这里如果用stringbuffer 会有问题
try {
URL url = new URL(domain+imgPath);
URLConnection con = url.openConnection();
con.setReadTimeout(60000);
con.setConnectTimeout(60000);
InputStream in = con.getInputStream();
final int bufferSize = 1024;
byte[] buffer = new byte[bufferSize];
int rsz = -1;
while ((rsz = in.read(buffer))>-1) {
out.write(buffer,0,rsz);
}
in.close();
} catch (IOException e) {
e.printStackTrace();
}
data = out.toByteArray();
// 对字节数组进行Base64编码,得到Base64编码的字符串
BASE64Encoder encoder = new BASE64Encoder();
String base64Str = encoder.encode(data);
//暂时没用,只是测试了下
// BASE64Decoder decoder = new BASE64Decoder();
// try {
// byte[] b = decoder.decodeBuffer(base64Str);
// File file = new File("d://abc.jpg");
// FileOutputStream o = new FileOutputStream(file);
//
// o.write(b);
// o.flush();
// o.close();
// } catch (IOException e) {
// e.printStackTrace();
// }finally {
//
// }
return base64Str;
}