2016-03-28 297 views
2

我試圖從cameraRoll上傳圖片。事情是cameraRoll組件返回content:// URI而不是實際的文件路徑。爲了上傳圖片我需要一個文件路徑,有什麼辦法將content:// URI轉換爲文件URI嗎?謝謝將React-Native轉換爲Android的實際路徑內容:// URI爲實際路徑

+0

爲什麼你需要一條路徑?你不能使用'InputStream'嗎? – pskink

+0

我正在開發一個React-Native應用程序,並且使用Java方法有點麻煩,所以我正在尋找一個反應原生解決方案。謝謝 – cubbuk

回答

6

我把提交@Madhukar Hebbar功能,使它成爲一個陣營本地節點模塊。

你可以在這裏找到:react-native-get-real-path

從而達到你想要什麼,你可以結合使用上述模塊react-native-fs

然後,您可以做這樣的事情,當你要上傳的選擇來自相機膠捲的圖像:

RNGRP.getRealPathFromURI(this.state.selectedImageUri).then(path => 
    RNFS.readFile(path, 'base64').then(imageBase64 => 
    this.props.actions.sendImageAsBase64(imageBase64) 
) 
) 
+0

你是救世主!只有一個問題 - 因爲它只適用於android - 需要將require包行放入平臺檢查邏輯中。然而,與它提供的效用相比 - 我可以忽略這一點。 :-) –

+0

我已經使用過你的圖書館,但沒有成功。我收到一個錯誤,「undefined不是一個函數(reactNativeGetRealPath2.default.getRealPathFromUri(path))',我給的路徑是content://com.google.android.apps.photos.contentprovider/-1/1 /內容%3A%2F%2Fmedia%2Fexternal%2Fimages%2Fmedia%2F890/ORIGINAL/NONE/225703422' –

0

content:// URI傳遞給下面的方法來獲取文件路徑作爲字符串,然後使用文件對象來執行任何操作。

File file = new File(getURIPath(uriValue)); 

/** 
* URI Value 
* @return File Path. 
*/ 
String getURIPath(Uri uriValue) 
    { 
     String[] mediaStoreProjection = { MediaStore.Images.Media.DATA }; 
     Cursor cursor = getContentResolver().query(uriValue, mediaStoreProjection, null, null, null); 
     if (cursor != null){ 
     int colIndex = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA); 
     cursor.moveToFirst(); 
     String colIndexString=cursor.getString(colIndex); 
     cursor.close(); 
     return colIndexString; 
     } 
     return null; 
    }