Reputation: 95
I am trying to download a file from a URL using an Asynctask. In the doInBackground() method, I retrieve the file size, like this.
lenghtOfFile = conection.getContentLength();
This returns an integer value. Now, the download continues and file is completely downloaded and written to sdcard.
The problem is that in my postExecute() I want to compare the size of the file from the URL and the size of the file downloaded.
@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()){
....
As you can see I log both values, but they are not equal even though the download ran to its end and the file was fully downloaded. The file from local storage(sdcard) ends up being greater than the file size from the url. I expect them to be equal, why is this happening? what can I do?
Below is the log result.
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
Thanks in advance.
Upvotes: 1
Views: 246
Reputation: 1064
Iv assumed that you are using HttpURLConnection
By default, this implementation of HttpURLConnection requests that servers use gzip compression and it automatically decompresses the data for callers of getInputStream()
. Therafore getContentLength()
cannot be used to determine size of file.
But! You can disable compression like this:
urlConnection.setRequestProperty("Accept-Encoding", "identity");
Your server should also be set to properly handle such case.
Upvotes: 1