Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -87,7 +87,15 @@ String getPathFromUri(final Context context, final Uri uri) {
String filePath = new File(targetDirectory, fileName).getPath();
File outputFile = saferOpenFile(filePath, targetDirectory.getCanonicalPath());
try (OutputStream outputStream = new FileOutputStream(outputFile)) {
copy(inputStream, outputStream);
long totalBytesCopied = copy(inputStream, outputStream);

Long expectedSize = getImageSize(context, uri);
if (expectedSize != null && expectedSize > 0 && totalBytesCopied < expectedSize) {
Log.w("FileUtils", "File copied is smaller than expected size (" + totalBytesCopied + " < " + expectedSize + "); deleting partial file.");
outputFile.delete();
return null;
}
Comment on lines +93 to +97

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

high

Attempting to delete outputFile while outputStream is still open can fail on some operating systems (like Windows) or filesystems because the file handle is still active. It is safer to close the stream before deleting the file.

        if (expectedSize != null && expectedSize > 0 && totalBytesCopied < expectedSize) {
          Log.w("FileUtils", "File copied is smaller than expected size (" + totalBytesCopied + " < " + expectedSize + "); deleting partial file.");
          try {
            outputStream.close();
          } catch (IOException ignored) {
          }
          outputFile.delete();
          return null;
        }


return outputFile.getPath();
}
} catch (IOException e) {
Expand Down Expand Up @@ -187,13 +195,26 @@ private static Cursor queryImageName(Context context, Uri uriImage) {
.query(uriImage, new String[] {MediaStore.MediaColumns.DISPLAY_NAME}, null, null, null);
}

private static void copy(InputStream in, OutputStream out) throws IOException {
private static Long getImageSize(Context context, Uri uriImage) {
try (Cursor cursor = context.getContentResolver().query(uriImage, new String[] {android.provider.OpenableColumns.SIZE}, null, null, null)) {
if (cursor == null || !cursor.moveToFirst() || cursor.getColumnCount() < 1) return null;
if (cursor.isNull(0)) return null;
return cursor.getLong(0);
} catch (Exception e) {
return null;
}
}
Comment thread
Suraj2105-1 marked this conversation as resolved.

private static long copy(InputStream in, OutputStream out) throws IOException {
final byte[] buffer = new byte[4 * 1024];
int bytesRead;
long total = 0;
while ((bytesRead = in.read(buffer)) != -1) {
out.write(buffer, 0, bytesRead);
total += bytesRead;
}
out.flush();
return total;
}

private static String getBaseName(String fileName) {
Expand Down
Loading