React-Native開發:react-native-file-selector選擇檔案元件的使用(安卓)
為了上傳檔案,搜尋了很多資料終於找到選擇本地檔案並獲取到具體路徑的元件,可以在github上查詢到該元件
以下為該元件使用前的引入工作:
1、npm install react-native-file-selector --save
2、react-native link react-native-file-selector
3、/app/build.gradle:
增加<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
4、MainApplication.java:
import ui.fileselector.RNFileSelectorPackage; // 增加這句
...
protected List<ReactPackage> getPackages() {
return Arrays.<ReactPackage>asList(
new MainReactPackage(),
new RNFileSelectorPackage(), // 增加這句
new PickerPackage()
);
}
...
5、增加檔案android/app/src/main/res/values/colors.xml:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<color name="colorPrimary">#3F51B5</color>
<color name="colorPrimaryDark">#303F9F</color>
<color name="colorAccent">#FF4081</color>
</resources>
6、android/build.gradle:
在allprojects的repositories中增加maven { url "http://dl.bintray.com/lukaville/maven" }
在該檔案末尾增加(這裡根據情況決定是否新增,我是在後來執行專案報錯時根據google搜尋到的方案新增的):
subprojects {
afterEvaluate {project ->
if (project.hasProperty("android")) {
android {
compileSdkVersion 25
buildToolsVersion '25.0.0'
}
}
}
}
7、settings.gradle:
include ':react-native-file-selector'
project(':react-native-file-selector').projectDir = new File(rootProject.projectDir, '../node_modules/react-native-file-selector/android')
8、使用方法:
import RNFileSelector from 'react-native-file-selector';
RNFileSelector.Show(
{
title: '請選擇檔案',
onDone: (path) => {
_uploadFile('file://' + path) // 根據官方給的fetch方法封裝的上傳方法
},
onCancel: () => {
console.log('cancelled')
}
}
)
9、關於上傳檔案或圖片到服務端,其實就是利用官方給的fetch方法,注意點是引數必須使用formData的形式,其中的檔案對應的資料是這樣的{ uri: filePath, type: ‘multipart/form-data’, name: fileName },其中的filePath是8中的檔案路徑。
ps:後期有需要再補充相關的get與post封裝(不過網上已經有很多了,可以自行百度或google)
10、上面的相關步驟(1-7)修改後可以嘗試看看能不能執行成功,不行的話就將專案中的node_modules移除並重新安裝依賴,嘗試在Android Studio rebuild一下,再重新執行試試,多試幾次就可以成功了。