【问题标题】:Get Uri filepath of a .pdf file获取 .pdf 文件的 Uri 文件路径
【发布时间】:2016-09-12 15:04:53
【问题描述】:

您好,我正在尝试获取我选择的 pdf 的真实文件路径,以便将其上传到服务器。

public void onActivityResult(int requestCode, int resultCode, Intent data) {

    super.onActivityResult(requestCode, resultCode, data);

    if (requestCode == SELECT_PDF_REQUEST_CODE) {getApplicationContext();
        if (resultCode == Activity.RESULT_OK) {

            Uri uri = data.getData();
            auxFile = new File(uri.getPath());
            pdfPath = auxFile.getAbsolutePath();

            Toast.makeText(getApplicationContext(),pdfPath,Toast.LENGTH_SHORT)
                    .show();


        } else {
            // failed to select file
            Toast.makeText(getApplicationContext(),
                    "Sorry! Failed to capture image", Toast.LENGTH_SHORT)
                    .show();
        }
    }
}

【问题讨论】:

  • 您的问题到底是什么?有什么问题?
  • 正在获取内容:/com.android.providers.downloads.documents/document/614,我无法将其上传到服务器
  • 那怎么了?有什么问题?
  • 文件的名称是 admin.pdf ,但我正在获取内容:/com.android.providers.downloads.documents/document/‌​614 我想获取真实文件以便我可以上传到服务器

标签: android pdf uri filepath


【解决方案1】:

我想得到真正的文件

没有“真正的文件”。你没有展示你用什么来得到这个结果,但大概是ACTION_GET_CONTENT。那,或ACTION_OPEN_DOCUMENT,不限于您可以访问的文件系统上的文件。他们可以返回一个Uri,该Uri 指向内容提供者想要的任何东西:加密内容、位于无法访问位置的文件、BLOB 列、需要下载的内容等等。用户选择内容,而不是您,并且用户可以从这些类型的来源中进行选择。

这样我就可以上传到服务器了

找到一些支持从Uri 上传的 HTTP API。

或者,使用ContentResolveropenInputStream() 在内容上获取InputStream,然后找到一些支持从InputStream 上传的HTTP API。

或者,使用ContentResolveropenInputStream() 在内容上获取InputStream,将该内容复制到某个临时文件(例如,在getCacheDir() 中),从临时文件上传,然后删除下载完成后的临时文件。

【讨论】:

  • 哦,好吧......可能是我做错了,但我已经能够解决它
【解决方案2】:

试试这个:

fun getPath(uri: Uri): String? {
            val isKitKat = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;

            // DocumentProvider
            if (isKitKat && DocumentsContract.isDocumentUri(context, uri)) {
                // ExternalStorageProvider
                if (isExternalStorageDocument(uri)) {
                    val docId = DocumentsContract.getDocumentId(uri);
                    val split = docId.split(":");
                    val type = split[0];

                    if ("primary".equals(type, true)) {
                        return Environment.getExternalStorageDirectory().path + "/" + split[1];
                    }
                    // TODO handle non-primary volumes
                }
                // DownloadsProvider
                else if (isDownloadsDocument(uri)) {
                    val id = DocumentsContract.getDocumentId(uri);
                    val contentUri = ContentUris.withAppendedId(Uri.parse("content://downloads/public_downloads"), Long.valueOf(id));
                    return getDataColumn(context, contentUri, null, null);
                }
                // MediaProvider
                else
                    if (isMediaDocument(uri)) {
                        val docId = DocumentsContract.getDocumentId(uri);
                        val split = docId.split(":");
                        val type = split[0];
                        var contentUri: Uri? = null;
                        if ("image" == type) {
                            contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
                        } else if ("video" == type) {
                            contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
                        } else if ("audio" == type) {
                            contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
                        }
                        val selection = "_id=?";
                        val selectionArgs = arrayOf(split[1])
                        return getDataColumn(context, contentUri, selection, selectionArgs);
                    }
            }
            // MediaStore (and general)
            else if ("content".equals(uri.getScheme(), true)) {
                // Return the remote address
                if (isGooglePhotosUri(uri))
                    return uri.getLastPathSegment();
                return getDataColumn(context, uri, null, null);
            }
            // File
            else if ("file".equals(uri.getScheme(), true)) {
                return uri.getPath();
            }
            return null;
        }

        fun getDataColumn(context: Context, uri: Uri?, selection: String?, selectionArgs: Array<String>?): String? {
            var cursor: Cursor? = null;
            val column = "_data";
            val projection = arrayOf(column);
            try {
                cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs, null);
                if (cursor != null && cursor.moveToFirst()) {
                    val index = cursor.getColumnIndexOrThrow(column);
                    return cursor.getString(index);
                }
            } finally {
                if (cursor != null)
                    cursor.close();
            }
            return null;
        }

        fun isExternalStorageDocument(uri: Uri): Boolean {
            return "com.android.externalstorage.documents" == uri.authority;
        }

        /**
         * @param uri The Uri to check.
         * @return Whether the Uri authority is DownloadsProvider.
         */
        fun isDownloadsDocument(uri: Uri): Boolean {
            return "com.android.providers.downloads.documents" == uri.authority;
        }

        /**
         * @param uri The Uri to check.
         * @return Whether the Uri authority is MediaProvider.
         */
        fun isMediaDocument(uri: Uri): Boolean {
            return "com.android.providers.media.documents" == uri.authority;
        }

        /**
         * @param uri The Uri to check.
         * @return Whether the Uri authority is Google Photos.
         */
        fun isGooglePhotosUri(uri: Uri): Boolean {
            return "com.google.android.apps.photos.content" == uri.authority;
        }

【讨论】:

    【解决方案3】:

    我在将该 pdf 文件复制到缓存目录后解决了问题 请在此处查看完整的解决方案:

    public static final String DOCUMENTS_DIR = "documents";
    
    if (isDownloadsDocument(uri)) {
    
                final String id = DocumentsContract.getDocumentId(uri);
    
                if (id != null && id.startsWith("raw:")) {
                    return id.substring(4);
                }
    
                String[] contentUriPrefixesToTry = new String[]{
                        "content://downloads/public_downloads",
                        "content://downloads/my_downloads"
                };
    
                for (String contentUriPrefix : contentUriPrefixesToTry) {
                    Uri contentUri = ContentUris.withAppendedId(Uri.parse(contentUriPrefix), Long.valueOf(id));
                    try {
                        String path = getDataColumn(context, contentUri, null, null);
                        if (path != null) {
                            return path;
                        }
                    } catch (Exception e) {}
                }
    
                // path could not be retrieved using ContentResolver, therefore copy file to accessible cache using streams
                String fileName = getFileName(context, uri);
                File cacheDir = getDocumentCacheDir(context);
                File file = generateFileName(fileName, cacheDir);
                String destinationPath = null;
                if (file != null) {
                    destinationPath = file.getAbsolutePath();
                    saveFileFromUri(context, uri, destinationPath);
                }
    
                return destinationPath;
            }
    
    public static String getFileName(@NonNull Context context, Uri uri) {
        String mimeType = context.getContentResolver().getType(uri);
        String filename = null;
    
        if (mimeType == null && context != null) {
            String path = getPath(context, uri);
            if (path == null) {
                filename = getName(uri.toString());
            } else {
                File file = new File(path);
                filename = file.getName();
            }
        } else {
            Cursor returnCursor = context.getContentResolver().query(uri, null, null, null, null);
            if (returnCursor != null) {
                int nameIndex = returnCursor.getColumnIndex(OpenableColumns.DISPLAY_NAME);
                returnCursor.moveToFirst();
                filename = returnCursor.getString(nameIndex);
                returnCursor.close();
            }
        }
    
        return filename;
    }
    
    public static String getName(String filename) {
        if (filename == null) {
            return null;
        }
        int index = filename.lastIndexOf('/');
        return filename.substring(index + 1);
    }
    
    public static File getDocumentCacheDir(@NonNull Context context) {
        File dir = new File(context.getCacheDir(), DOCUMENTS_DIR);
        if (!dir.exists()) {
            dir.mkdirs();
        }
    //        logDir(context.getCacheDir());
    //        logDir(dir);
    
        return dir;
    }
    
    @Nullable
    public static File generateFileName(@Nullable String name, File directory) {
        if (name == null) {
            return null;
        }
    
        File file = new File(directory, name);
    
        if (file.exists()) {
            String fileName = name;
            String extension = "";
            int dotIndex = name.lastIndexOf('.');
            if (dotIndex > 0) {
                fileName = name.substring(0, dotIndex);
                extension = name.substring(dotIndex);
            }
    
            int index = 0;
    
            while (file.exists()) {
                index++;
                name = fileName + '(' + index + ')' + extension;
                file = new File(directory, name);
            }
        }
    
        try {
            if (!file.createNewFile()) {
                return null;
            }
        } catch (IOException e) {
            //Log.w(TAG, e);
            return null;
        }
    
        //logDir(directory);
    
        return file;
    }
    
    private static void saveFileFromUri(Context context, Uri uri, String destinationPath) {
        InputStream is = null;
        BufferedOutputStream bos = null;
        try {
            is = context.getContentResolver().openInputStream(uri);
            bos = new BufferedOutputStream(new FileOutputStream(destinationPath, false));
            byte[] buf = new byte[1024];
            is.read(buf);
            do {
                bos.write(buf);
            } while (is.read(buf) != -1);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (is != null) is.close();
                if (bos != null) bos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    

    感谢对此thread的帮助

    【讨论】:

      【解决方案4】:
      @Override
      
      public void onActivityResult(int requestCode, int resultCode, Intent data) {
      
          super.onActivityResult(requestCode, resultCode, data);
      
          if (requestCode == SELECT_IMAGE_REQUEST_CODE) {getApplicationContext();
              if (resultCode == Activity.RESULT_OK) {
      
      
      
                  if(data == null){
                      //no data present
                      return;
                  }
      
      
                  Uri selectedFileUri = data.getData();
                  fPath= FilePath.getPath(this,selectedFileUri);
                  Log.i(TAG, "Selected File Path:" + fPath);
      
                  if(fPath!= null && !fPath.equals("")){
                      tv.setText(fPath);
                  }else{
                      Toast.makeText(this,"Cannot upload file to server",Toast.LENGTH_SHORT).show();
                  }
      
      
      
      
      
      
      
                  tv.setText(fPath);
      
              } else {
                  // failed to select file
                  Toast.makeText(getApplicationContext(),
                          "Sorry! Failed to select file", Toast.LENGTH_SHORT)
                          .show();
              }
          }
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-12-08
        • 1970-01-01
        • 2020-03-26
        相关资源
        最近更新 更多