文件下载是开发中比较常见的功能,当后端无法告诉前端下载文件大小时,就需要前端自己获取文件大小
简单的方法为:
final URLConnection connection = url.openConnection();
final int length = connection.getContentLength();
当文件比较多且文件较大时,使用getContentLength()获取大小你会发现,神马情况?太NM慢了
记录一下解决文件下载前获取多个网络文件总大小时太慢的问题
private long getAllFileLength(String[] fileList){
try {
URL u = null;
long fileLength = 0;
for (int i=0;i<fileList.length;i++){
u = new URL(fileList[i]);
HttpURLConnection urlcon = (HttpURLConnection) u.openConnection();
fileLength = fileLength + handleFileLen(urlcon.getHeaderFields());
}
return fileLength;
} catch (MalformedURLException e) {
e.printStackTrace();
return 0;
} catch (IOException e) {
e.printStackTrace();
return 0;
}
}
public long handleFileLen(Map<String, List<String>> headers) {
if (headers == null || headers.isEmpty()) {
Log.e(TAG, "header为空,获取文件长度失败");
return -1;
}
List<String> sLength = headers.get("Content-Length");
if (sLength == null || sLength.isEmpty()) {
return -1;
}
String temp = sLength.get(0);
long len = TextUtils.isEmpty(temp) ? -1 : Long.parseLong(temp);
// 某些服务,如果设置了conn.setRequestProperty("Range", "bytes=" + 0 + "-");
// 会返回 Content-Range: bytes 0-225427911/225427913
if (len < 0) {
List<String> sRange = headers.get("Content-Range");
if (sRange == null || sRange.isEmpty()) {
len = -1;
} else {
int start = temp.indexOf("/");
len = Long.parseLong(temp.substring(start + 1));
}
}
return len;
}