Skip to content

Commit 667ff2c

Browse files
committed
Use ParcelFileDescriptor for resolving filesize
1 parent b24f52b commit 667ff2c

File tree

1 file changed

+25
-4
lines changed

1 file changed

+25
-4
lines changed

tus-android-client/src/main/java/io/tus/android/client/TusAndroidUpload.java

Lines changed: 25 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,31 +1,52 @@
11
package io.tus.android.client;
22

33
import android.app.Activity;
4+
import android.content.ContentResolver;
45
import android.database.Cursor;
56
import android.net.Uri;
7+
import android.os.ParcelFileDescriptor;
68
import android.provider.OpenableColumns;
9+
import android.util.Log;
710

811
import java.io.FileNotFoundException;
12+
import java.io.IOException;
913
import java.util.HashMap;
1014
import java.util.Map;
1115

1216
import io.tus.java.client.TusUpload;
1317

1418
public class TusAndroidUpload extends TusUpload {
1519
public TusAndroidUpload(Uri uri, Activity activity) throws FileNotFoundException {
16-
Cursor cursor = activity.getContentResolver().query(uri, new String[]{OpenableColumns.SIZE, OpenableColumns.DISPLAY_NAME}, null, null, null);
20+
ContentResolver resolver = activity.getContentResolver();
21+
Cursor cursor = resolver.query(uri, new String[]{OpenableColumns.SIZE, OpenableColumns.DISPLAY_NAME}, null, null, null);
1722
if(cursor == null) {
1823
throw new FileNotFoundException();
1924
}
2025

21-
int sizeIndex = cursor.getColumnIndex(OpenableColumns.SIZE);
2226
int nameIndex = cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME);
2327
cursor.moveToFirst();
24-
long size = cursor.getLong(sizeIndex);
2528
String name = cursor.getString(nameIndex);
2629

30+
// On some files, ContentResolver#query will report the wrong filesize
31+
// even though the InputStream reads the correct length. This discrepancy
32+
// causes mismatching upload offsets when the upload should be finished.
33+
// Using the stat size from a file descriptor seems to always report the
34+
// correct filesize.
35+
// See https://github.com/tus/tus-android-client/issues/25
36+
// See https://stackoverflow.com/questions/21882322/how-to-correctly-get-the-file-size-of-an-android-net-uri
37+
ParcelFileDescriptor fd = resolver.openFileDescriptor(uri, "r");
38+
if(fd == null) {
39+
throw new FileNotFoundException();
40+
}
41+
long size = fd.getStatSize();
42+
try {
43+
fd.close();
44+
} catch (IOException e) {
45+
Log.e("TusAndroidUpload", "unable to close ParcelFileDescriptor", e);
46+
}
47+
2748
setSize(size);
28-
setInputStream(activity.getContentResolver().openInputStream(uri));
49+
setInputStream(resolver.openInputStream(uri));
2950

3051
setFingerprint(String.format("%s-%d", uri.toString(), size));
3152

0 commit comments

Comments
 (0)