文件下載是開發(fā)中比較常見的功能推盛,當(dāng)后端無法告訴前端下載文件大小時(shí)耘成,就需要前端自己獲取文件大小
簡單的方法為:
final URLConnection connection = url.openConnection();
final int length = connection.getContentLength();
當(dāng)文件比較多且文件較大時(shí),使用getContentLength()獲取大小你會(huì)發(fā)現(xiàn)撒会,神馬情況师妙?太NM慢了
記錄一下解決文件下載前獲取多個(gè)網(wǎng)絡(luò)文件總大小時(shí)太慢的問題
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);
// 某些服務(wù)怔檩,如果設(shè)置了conn.setRequestProperty("Range", "bytes=" + 0 + "-");
// 會(huì)返回 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;
}