Search code examples
androidandroid-contentresolverstorage-access-framework

How can I copy a file from Dropbox/Drive/Onedrive to a specific path using getContentResolver().openFileDescriptor() from Storage Access Framework?


I'm trying to copy a file from a generic hosting file service as Dropbox/Drive/Onedrive to a specific path in my device.

I created a working example to copy a jpg file, but what I would like to create is a version for copying these types: .docx, .pdf, .pptx, .jpg, .jpeg, .png, .gif, .mp3, .mp4, .xlsx.

What do I have to do? How can I modify my code?

Thanks

// the flow start from here
public void newFile() {
    Intent intent = new Intent();
    intent.setType("image/*");
    intent.setAction(Intent.ACTION_GET_CONTENT);
    startActivityForResult(Intent.createChooser(intent, "Select file"), NEW_FILE_PRIVATE);
}

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    if (requestCode == NEW_FILE_PRIVATE && resultCode == Activity.RESULT_OK) {
        if (data != null) {
            Uri currentUri = null;
            currentUri = data.getData();

            String contentString = currentUri.toString();

            if (contentString.contains("com.dropbox.android") ||
                contentString.contains("com.microsoft.skydrive") ||
                contentString.contains("com.google.android.apps.docs.storage")) {
                try {
                    copyFileContent(currentUri);
                } catch (IOException e) {
                    Log.e("cloud error", "error");
                }
            }
        }
    }
}

private String copyFileContent(Uri uri) throws IOException {

    ParcelFileDescriptor pFileDescriptor = getContentResolver().openFileDescriptor(uri, "r");

    FileDescriptor fileDescriptor = pFileDescriptor.getFileDescriptor();

    Bitmap image = BitmapFactory.decodeFileDescriptor(fileDescriptor);

    pFileDescriptor.close();

    /* temporary path */
    String extension = getMimeType(getApplicationContext(), uri);

    String temporaryFilePath = Environment.getExternalStorageDirectory().toString()
            .concat("/").concat("temporaryfile")
            .concat(".").concat(extension);

    File file = new File(temporaryFilePath);

    OutputStream outStream = null;

    try {
        /* make a new bitmap from your file */

        outStream = new FileOutputStream(file);
        image.compress(Bitmap.CompressFormat.JPEG, 100, outStream);
        outStream.flush();
        outStream.close();

    } catch (Exception e) {
        e.printStackTrace();
    }

    return temporaryFilePath;
}

Edit Thanks to @CommonsWare I wrote a solution for getting the file extension using this code:

public String getExtension(Context context, Uri uri) {
    String extension;

    if (uri.getScheme().equals(ContentResolver.SCHEME_CONTENT)) {
        final MimeTypeMap mime = MimeTypeMap.getSingleton();
        extension = mime.getExtensionFromMimeType(context.getContentResolver().getType(uri));
    } else {
        extension = MimeTypeMap.getFileExtensionFromUrl(Uri.fromFile(new File(uri.getPath())).toString());
    }

    return extension;
}

Edit 2 With the help of @Greenapps I implemented this solution:

private String copyFileContent(Uri uri) throws IOException {

    InputStream inputStream = getContentResolver().openInputStream(uri);

    /* temporary path */
    String extension = getMimeType(getApplicationContext(), uri);
    String temporaryFilePath = Environment.getExternalStorageDirectory().toString()
        .concat("/").concat("temporaryfile")
        .concat(".").concat(extension);

    OutputStream outStream = new FileOutputStream(temporaryFilePath);

    final byte[] b = new byte[8192];
    for (int r;(r = inputStream.read(b)) != -1;) outStream.write(b, 0, r);

    return temporaryFilePath;
}

Does exists a method for getting the filename instead of naming it "temporary file"?

Edit 3

private String copyFileContent(Uri uri) throws IOException {
    InputStream inputStream = getContentResolver().openInputStream(uri);

    String uriString = uri.toString();
    String fileName = "";
    if (!uriString.contains("com.dropbox.android")) {
        Cursor returnCursor = getContentResolver().query(uri, null, null, null, null);
        int nameIndex = returnCursor.getColumnIndex(OpenableColumns.DISPLAY_NAME);
        returnCursor.moveToFirst();
        fileName = returnCursor.getString(nameIndex);
    } else {
        fileName = uriString.substring(uriString.lastIndexOf("/") + 1, uriString.lastIndexOf("."));
    }

    /* temporary path */
    String extension = getMimeType(getApplicationContext(), uri);
    String temporaryFilePath = Environment.getExternalStorageDirectory().toString()
        .concat("/").concat(egoName)
        .concat("/").concat("PRIVATE")
        .concat("/").concat(fileName)
        .concat(".").concat(extension);

    OutputStream outStream = new FileOutputStream(temporaryFilePath);

    final byte[] b = new byte[8192];
    for (int r;
        (r = inputStream.read(b)) != -1;) outStream.write(b, 0, r);

    return temporaryFilePath;
}

Solution

  • After about a day it was clear that you just want to copy files.

    Do it in the normal way by opening an InputStream.

     InputStream is = getContentResolver().openInputStream(uri);
    

    Then read chuncks from the stream and write them to a FileOutputStream.

    As DropBox is full of files the filename (with extension) can be found in data.getData().getPath(). But using the display name column is a better idea.