2017-10-09 30 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