React Native 打开手机的相册和相机react
安装模块
yarn add react-native-image-picker
react-native link react-native-image-picker
复制代码
使用例子android
import ImagePicker from 'react-native-image-picker';
// More info on all the options is below in the API Reference... just some common use cases shown here
const options = {
title: 'Select Avatar',
customButtons: [{ name: 'fb', title: 'Choose Photo from Facebook' }],
storageOptions: {
skipBackup: true,
path: 'images',
},
};
/**
* The first arg is the options object for customization (it can also be null or omitted for default options),
* The second arg is the callback which sends object: response (more info in the API Reference)
*/
ImagePicker.showImagePicker(options, (response) => {
console.log('Response = ', response);
if (response.didCancel) {
console.log('User cancelled image picker');
} else if (response.error) {
console.log('ImagePicker Error: ', response.error);
} else if (response.customButton) {
console.log('User tapped custom button: ', response.customButton);
} else {
const source = { uri: response.uri };
// You can also display the image using data:
// const source = { uri: 'data:image/jpeg;base64,' + response.data };
this.setState({
avatarSource: source,
});
// 进行文件提交
uploadImage(response)
}
});
复制代码
咱们采用rn-fetch-blob模块进行文件上传ios
安装模块
npm install --save rn-fetch-blob
关联模块
react-native link
安卓权限配置
RNFB_ANDROID_PERMISSIONS=true react-native link
复制代码
使用例子git
注意ios和android的路径区别
uploadImage = (response) => {
const PATH = Platform.OS === 'android' ? response.uri : response.uri.replace('file:///', '')
RNFetchBlob.fetch('POST', '/api/other/file/upload', {
'Content-Type': 'multipart/form-data',
}, [
{
name: 'file1',
filename: response.fileName || '未命名文件.jpg',
type: response.type,
data: RNFetchBlob.wrap(PATH)
}
]).then((resp) => {
// ...
console.log(resp, 'resp')
}).catch((err) => {
// ...
console.log(err, 'err')
})
}
复制代码