簡體   English   中英

如何在 Android Oreo (8.1) 或更高版本中從 URI 獲取文件路徑

[英]How to Get File Path from URI in Android Oreo (8.1) or above

預期行為

當我選擇存儲在“下載”中的文件時,它應該能夠檢索其文件名和路徑

實際行為

當我選擇存儲在“下載”中的文件時,它返回空值。

重現問題的步驟

  1. 當picking file方法被調用時,它會顯示Android中的文件夾
  2. 轉到下載,選擇一個文件
  3. 從 URI 獲取真實路徑時返回 null

這是我實現的代碼

public static String getPath(final Context context, final Uri uri) {
   String id = DocumentsContract.getDocumentId(uri);
   if (!TextUtils.isEmpty(id)) {
      if (id.startsWith("raw:")) {
          return id.replaceFirst("raw:", "");
      }
      try {
         final boolean isOreo = Build.VERSION.SDK_INT >= Build.VERSION_CODES.O;
         String stringContentURI;
         Uri contentUri;
         if(isOreo){ 
            stringContentURI = "content://downloads/my_downloads";
         }else{
            stringContentURI = "content://downloads/public_downloads";
         }
         contentUri = ContentUris.withAppendedId(
                    Uri.parse(stringContentURI), Long.valueOf(id));
         return getDataColumn(context, contentUri, null, null);
      } catch (NumberFormatException e) {
         return null;
      }
   }
}

public 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;
}

但是,它在從 Android 設備的其他文件夾中選擇文件時有效

請指教。 謝謝大家 :)

目前,獲取路徑的最佳方法是:

從 URI 獲取物理文件作為 InputStream, ContentResolver.openInputStream()允許您在不知道其真實路徑的情況下訪問文件的內容

String id = DocumentsContract.getDocumentId(uri);
InputStream inputStream = getContentResolver().openInputStream(uri);

然后將其作為臨時文件寫入緩存存儲

File file = new File(getCacheDir().getAbsolutePath()+"/"+id);
writeFile(inputStream, file);
String filePath = file.getAbsolutePath();

這是將臨時文件寫入緩存存儲的方法

void writeFile(InputStream in, File file) {
     OutputStream out = null;
     try {
          out = new FileOutputStream(file);
          byte[] buf = new byte[1024];
          int len;
          while((len=in.read(buf))>0){
            out.write(buf,0,len);
          }
     } catch (Exception e) {
          e.printStackTrace();
     }
     finally {
          try {
            if ( out != null ) {
                 out.close();
            }
            in.close();
          } catch ( IOException e ) {
               e.printStackTrace();
          }
     }
}

不確定它是否是最好的方法,但代碼工作正常:D

這是活動實例變量

*************************************************************************
*************************************************************************  

    Uri filePath;
    String strAttachmentFileName = "",//attached file name
            strAttachmentCoded = "";//attached file in byte code Base64
    int PICK_REQUEST =1;
*************************************************************************
*************************************************************************  

這是活動方法

*************************************************************************
*************************************************************************  

Button buttonChoose.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent();
                intent.setType("file/*");
                intent.setAction(Intent.ACTION_GET_CONTENT);
                startActivityForResult(Intent.createChooser(intent, "Select any file"), PICK_REQUEST );
            }
        });
*************************************************************************
*************************************************************************  

這是覆蓋活動方法

*************************************************************************
*************************************************************************



    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == PICK_REQUEST && resultCode == Activity.RESULT_OK && data != null && data.getData() != null) {
            filePath = data.getData();
            File uploadFile = new File(FileUtils.getRealPath(activity.this, filePath));
            try {
                if (uploadFile != null) {
                    strAttachmentFileName = uploadFile.getName();
                    FileInputStream objFileIS = new FileInputStream(uploadFile);
                    ByteArrayOutputStream objByteArrayOS = new ByteArrayOutputStream();
                    byte[] byteBufferString = new byte[1024];
                    int readNum;
                    readNum = objFileIS.read(byteBufferString);
                    while (readNum != -1) {
                        objByteArrayOS.write(byteBufferString, 0, readNum);
                        readNum = objFileIS.read(byteBufferString);
                    }
                    strAttachmentCoded  = Base64.encodeToString(objByteArrayOS.toByteArray(), Base64.DEFAULT);

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

*************************************************************************
*************************************************************************  

請創建文件 FileUtils.java 如下

鏈接 HBiSoft



對於 .Net 中的任何類型的文件 ---
 byte[] p = Convert.FromBase64String("byte string"); MemoryStream ms = new MemoryStream(p); FileStream fs = new FileStream (System.Web.Hosting.HostingEnvironment.MapPath("~/ComplaintDetailsFile/") + item.FileName, FileMode.Create); ms.WriteTo(fs); ms.Close(); fs.Close(); fs.Dispose();

這是我從這個要點中找到的另一個解決方案。 文件實用程序

這是如何使用它。

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    Uri uri = data.getData();
    File originalFile = new File(FileUtils.getRealPath(this,uri));
}

這就是我剛剛想到的(它在 Android Pie 上進行了測試,並假設有一張 SD 卡):

private String getParentDirectory(@NonNull Uri uri) {
    String uriPath = uri.getPath();
    String filePath = Environment.getExternalStorageDirectory().getAbsolutePath();
    if(uriPath != null) {filePath = new File(filePath.concat("/" + uriPath.split(":")[1])).getParent();}
    return filePath;
}

private String getAbsolutePath(@NonNull Uri uri) {
    String uriPath = uri.getPath();
    String filePath = Environment.getExternalStorageDirectory().getAbsolutePath();
    if(uriPath != null) {filePath = filePath.concat("/" + uriPath.split(":")[1]);}
    return filePath;
}

下面的 API 會很有用。我們需要在我們的應用程序的緩存中創建文件並返回相同的路徑,因為限制,即范圍存儲。

fun createFileAndGetPathFromCacheFolder(context: Context, uri: Uri): String? {
    var inputStream: FileInputStream? = null
    var outputStream: FileOutputStream? = null
    try {
        val parcelFileDescriptor = context.contentResolver.openFileDescriptor(uri, "r", null)
        inputStream = FileInputStream(parcelFileDescriptor?.fileDescriptor)
        val file = File(context.cacheDir, context.contentResolver.getFileName(uri))
        outputStream = FileOutputStream(file)
        val buffer = ByteArray(1024)
        var len: Int
        while (inputStream.read(buffer).also { len = it } != -1) {
            outputStream.write(buffer, 0, len)
        }
        return file.absolutePath
    } catch (e: Exception) {

    } finally {
        inputStream?.close()
        outputStream?.close()
    }
    return " "
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM