来自 URL 的文件大小与存储中的下载文件不同
File size from URL not the same as download file in storage
我正在尝试使用 Asynctask 从 URL 下载文件。在 doInBackground() 方法中,我检索文件大小,如下所示。
lenghtOfFile = conection.getContentLength();
这returns一个整数值。现在,下载继续,文件已完全下载并写入 sdcard。
问题是在我的 postExecute() 中,我想比较来自 URL 的文件的大小和下载的文件的大小。
@Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
//check if the file was download and know how much of it
//was downloaded, so as to update ui accordingly
if(file.exists()){
Log.e("apiFileSize", String.valueOf(lenghtOfFile));
Log.e("downloadFileSize", String.valueOf(file.length()));
//check if the file was completely downloaded
if(lenghtOfFile == file.length()){
....
如您所见,我记录了两个值,但即使下载 运行 结束并且文件已完全下载,它们也不相等。来自本地存储(sdcard)的文件最终大于来自 url 的文件大小。我希望他们是平等的,为什么会这样?我能做什么?
下面是日志结果。
09-23 22:44:48.203 26594-26594/com.mobile.soullounge E/apiFileSize﹕ 1298573
09-23 22:44:48.204 26594-26594/com.mobile.soullounge E/downloadedFileSize﹕ 2696392
提前致谢。
我假设您正在使用 HttpURLConnection
默认情况下,此 HttpURLConnection 实现请求服务器使用 gzip 压缩,并自动解压缩 getInputStream()
调用者的数据。 Therafore getContentLength()
不能用于确定文件的大小。
但是!您可以像这样禁用压缩:
urlConnection.setRequestProperty("Accept-Encoding", "identity");
您的服务器也应该设置为正确处理这种情况。
我正在尝试使用 Asynctask 从 URL 下载文件。在 doInBackground() 方法中,我检索文件大小,如下所示。
lenghtOfFile = conection.getContentLength();
这returns一个整数值。现在,下载继续,文件已完全下载并写入 sdcard。
问题是在我的 postExecute() 中,我想比较来自 URL 的文件的大小和下载的文件的大小。
@Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
//check if the file was download and know how much of it
//was downloaded, so as to update ui accordingly
if(file.exists()){
Log.e("apiFileSize", String.valueOf(lenghtOfFile));
Log.e("downloadFileSize", String.valueOf(file.length()));
//check if the file was completely downloaded
if(lenghtOfFile == file.length()){
....
如您所见,我记录了两个值,但即使下载 运行 结束并且文件已完全下载,它们也不相等。来自本地存储(sdcard)的文件最终大于来自 url 的文件大小。我希望他们是平等的,为什么会这样?我能做什么?
下面是日志结果。
09-23 22:44:48.203 26594-26594/com.mobile.soullounge E/apiFileSize﹕ 1298573
09-23 22:44:48.204 26594-26594/com.mobile.soullounge E/downloadedFileSize﹕ 2696392
提前致谢。
我假设您正在使用 HttpURLConnection
默认情况下,此 HttpURLConnection 实现请求服务器使用 gzip 压缩,并自动解压缩 getInputStream()
调用者的数据。 Therafore getContentLength()
不能用于确定文件的大小。
但是!您可以像这样禁用压缩:
urlConnection.setRequestProperty("Accept-Encoding", "identity");
您的服务器也应该设置为正确处理这种情况。