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')
})
}
複製代碼