React-Native开发:react-native-file-selector选择文件组件的使用(安卓)
为了上传文件,搜索了很多资料终于找到选择本地文件并获取到具体路径的组件,可以在github上查找到该组件以下为该组件使用前的引入工作:1、npm install react-native-file-selector --save2、react-native link react-native-file-selector3、/app/build.gradle:增加<...
为了上传文件,搜索了很多资料终于找到选择本地文件并获取到具体路径的组件,可以在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一下,再重新运行试试,多试几次就可以成功了。
更多推荐
所有评论(0)