2017-10-09 117 views
0

我想從我的應用程序上傳文件到服務器。用戶被允許從他的內部存儲器附加文件。但是一些我從牛軋糖手機獲得的路徑與標準/storage/emulated/0/...不同。在少數電話中,我得到external_files/...,而在其他電話中我得到root_files/storage/999/....。在這種情況下,我沒有找到正確的文件路徑。我們如何處理這種情況?附加文件並上傳到服務器 - Android Nougat

我的代碼:

@Override 
public void onActivityResult(int requestCode, int resultCode, Intent data) { 
    if (resultCode == RESULT_OK) { 
     Uri selectedImageUri = data.getData(); 
     String filePath = data.getData().getPath(); 
     File sourceFile = new File(fileFields.get(i).getFileName()); 
     FileInputStream fileInputStream = new FileInputStream(sourceFile); 
    } 
} 

回答

0

一個Uri不是一個文件。 getPath()是沒有意義的,除非Uri的方案碰巧是file。這在新款Android設備上不會很常見。相反,該計劃將爲content,而getPath()對您無用。

相反,對於filecontentUri值,使用ContentResolveropenInputStream()獲得由Uri標識內容的InputStream。這種方法可以一直回到Android 1.0。

+0

請你分享我一個例子嗎?我嘗試過使用'ContentResolver',但是我得到'NPE'在'cursor.moveToFirst()' –

+0

@SahanaPrabhakar:我的答案不涉及'Cursor'。我說要調用'openInputStream()'。 'openInputStream()'不返回一個'Cursor'。 'openInputStream()'返回一個'InputStream'。因此,'getContentResolver()。openInputStream(selectedImageUri)'爲'Uri'標識的內容提供'InputStream'。 – CommonsWare