从Google驱动器的文件选择器中获取正确的URI

3
这里是我的问题,我需要获取手机中的一个文件并将其上传到我的parse-server。我已经为文档、下载、外部和媒体文件夹制作了一个文件选择器,但是android文件选择器也提供了GoogleDrive选项。所以我得到了Uri但找不到访问“本地副本”的方法。
我需要使用GoogleDrive SDK来访问它吗?还是android可以聪明到给我处理那个Uri的方法?
我已成功获取文件名。
content://com.google.android.apps.docs.storage/document/

这是我的文件选择器和处理程序:

public static void pick(final Controller controller) {
        final Intent chooseFileIntent = new Intent(Intent.ACTION_GET_CONTENT);
        chooseFileIntent.setType("application/pdf");
        chooseFileIntent.addCategory(Intent.CATEGORY_OPENABLE);
        if (chooseFileIntent.resolveActivity(controller.getContext().getPackageManager()) != null) {
            controller.startActivityForResult(chooseFileIntent, Configuration.Request.Code.Pdf.Pdf);
        }
    }

    private static boolean isExternalStorageDocument(Uri uri) {
        return "com.android.externalstorage.documents".equals(uri.getAuthority());
    }

    private static boolean isDownloadsDocument(Uri uri) {
        return "com.android.providers.downloads.documents".equals(uri.getAuthority());
    }

    private static boolean isMediaDocument(Uri uri) {
        return "com.android.providers.media.documents".equals(uri.getAuthority());
    }

    private static boolean isGooglePhotosUri(Uri uri) {
        return "com.google.android.apps.photos.content".equals(uri.getAuthority());
    }

    private static boolean isGoogleDriveUri(Uri uri) {
        return "com.google.android.apps.docs.storage".equals(uri.getAuthority());
    }

    private static String getDataColumn(Context context, Uri uri, String selection, String[] selectionArgs) {
        Cursor cursor = null;
        final String column = "_data";
        final String[] projection = { column };
        try {
            cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs, null);
            if (cursor != null && cursor.moveToFirst()) {
                final int index = cursor.getColumnIndexOrThrow(column);
                return cursor.getString(index);
            }
        } finally {
            if (cursor != null)
                cursor.close();
        }
        return null;
    }

    private static String getPath(Context context, Uri uri) {
        if (DocumentsContract.isDocumentUri(context, uri)) {
            if (isExternalStorageDocument(uri)) {
                final String docId = DocumentsContract.getDocumentId(uri);
                final String[] split = docId.split(":");
                final String type = split[0];

                if ("primary".equalsIgnoreCase(type)) {
                    return Environment.getExternalStorageDirectory() + "/" + split[1];
                }
            } else if (isGoogleDriveUri(uri)) {
//                Cursor cursor = context.getContentResolver().query(uri, null, null, null, null);
//                if (cursor != null) {
//                    int fileNameIndex = cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME);
//                    cursor.moveToFirst();
//                    Log.d("=== TAG ===", cursor.getString(fileNameIndex));
//                    Log.d("=== TAG ===", uri.getPath());
//                    cursor.close();
//                }
            } else if (isDownloadsDocument(uri)) {
                final String id = DocumentsContract.getDocumentId(uri);
                final Uri contentUri = ContentUris.withAppendedId(Uri.parse("content://downloads/public_downloads"), Long.valueOf(id));
                return getDataColumn(context, contentUri, null, null);
            } else if (isMediaDocument(uri)) {
                final String docId = DocumentsContract.getDocumentId(uri);
                final String[] split = docId.split(":");
                final String type = split[0];
                Uri contentUri = null;
                if ("image".equals(type)) {
                    contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
                } else if ("video".equals(type)) {
                    contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
                } else if ("audio".equals(type)) {
                    contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
                }
                final String selection = "_id=?";
                final String[] selectionArgs = new String[] {split[1]};
                return getDataColumn(context, contentUri, selection, selectionArgs);
            }
        }
        else if ("content".equalsIgnoreCase(uri.getScheme())) {
            if (isGooglePhotosUri(uri))
                return uri.getLastPathSegment();
            return getDataColumn(context, uri, null, null);
        }
        else if ("file".equalsIgnoreCase(uri.getScheme())) {
            return uri.getPath();
        }
        return null;
    }

    public static void upload(final Context context, final String name, final ParseObject dataSource, final String field, final Uri uri, final Handler handler) {
        if (context != null && name != null && dataSource != null && field != null && uri != null) {
            String path = getPath(context, uri);
            if (path != null) {
                final File file = new File(path);
                dataSource.put(field, new ParseFile(file));
                dataSource.getParseFile(field).saveInBackground(new SaveCallback() {
                    @Override
                    public void done(ParseException e) {
                        if (e == null) {
                            if (handler != null) {
                                handler.success();
                            }
                        }
                    }
                }, new ProgressCallback() {
                    @Override
                    public void done(Integer percentDone) {
                        if (handler != null) {
                            handler.progress(percentDone);
                        }
                    }
                });
            }
        }
    }

编辑:

我尝试了一些方法,但是在删除临时文件时遇到了问题。以下是我的代码:

public static void copyFile(final Context context, final Uri uri, final ParseObject dataSource, final String field, final String name, final Data.Source target, final Handler handler) {
        new AsyncTask<Void, Void, Boolean>() {
            @Override
            protected Boolean doInBackground(Void... params) {
                try {
                    InputStream inputStream = context.getContentResolver().openInputStream(uri);
                    if (inputStream != null) {
                        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
                        byte[] bytes = new byte[1024];
                        int length;
                        while ((length = inputStream.read(bytes)) != -1)  {
                            byteArrayOutputStream.write(bytes, 0, length);
                        }
                        dataSource.put(field, new ParseFile(name, byteArrayOutputStream.toByteArray()));
                        byteArrayOutputStream.close();
                        inputStream.close();
                        return true;
                    } else {
                        return false;
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                    return false;
                }
            }

            @Override
            protected void onPostExecute(final Boolean success) {
                dataSource.getParseFile(field).saveInBackground(new SaveCallback() {
                    @Override
                    public void done(ParseException e) {
                        if (e == null) {
                            if (handler != null) {
                                handler.success();
                            }
                        }
                    }
                }, new ProgressCallback() {
                    @Override
                    public void done(Integer percentDone) {
                        if (handler != null) {
                            handler.progress(percentDone);
                        }
                    }
                });
            }
        }.execute();
    }

最终编辑:

在这里,我的代码是正确的,临时文件由Parse自己创建并放入缓存中,所以超出了我的范围。希望他可以提供帮助。

1个回答

3
所以我有URI,但我找不到访问那个“本地副本”的方法。

没有“本地副本”,至少你无法访问。

或者安卓不能聪明一些,给我处理那个URI的方法?

使用ContentResolveropenInputStream()获取由Uri标识的内容上的InputStream。直接使用它与你的“parse-server”一起使用,或使用它创建一个临时的“本地副本”到你控制的文件中。上传该本地副本,在完成后删除它。

这是我的文件选择器和处理程序:

pick()没问题。upload()可能没问题;我没有使用过Parse。代码的其余部分是垃圾,从之前的垃圾复制而来。它做出了许多毫无根据、不可靠的假设,并且对于来自任意应用程序的Uri值(例如通过FileProvider提供),它将无效。


你有适用于大多数Uri的解决方案吗?我需要使用第三方库吗?我没有时间实际开发所有这些。谢谢回答! - Nek
@Nek:“你有解决方案可以处理大多数Uri吗?”--根据定义,这是不可能的。带有“content”方案的Uri可以指向ContentProvider想要的任何内容,这不一定是一个文件,更不用说是一个你可以访问的文件系统上的文件了。使用ContentResolveropenInputStream()。"我没有时间实际开发所有这些" --从InputStream复制数据到FileOutputStream是微不足道的,这是在Java编程书籍中可以阅读到的东西。 - CommonsWare
好的,如果我理解正确,我应该做一个文件选择器,始终使用openInputStream和本地临时副本,以尽可能通用? - Nek
@Nek:如果Uri方案是contentandroid.resource,那么是的。如果Uri方案是file,那么你应该通过getPath()直接访问文件系统中的内容(假设其他应用程序没有弄错给你的Uri)。openInputStream()也可以处理file方案,因此如果您想将其视为与contentandroid.resource相同,则可以这样做。现在大多数情况下,您会得到content - CommonsWare
非常感谢您提供的所有信息,我会尝试一些方法,并在得到答案后在此发布! - Nek
显示剩余2条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接