主要借助两个开源库
1.选取和拍照
https://github.com/react-native-community/react-native-image-picker
2.上传
https://github.com/joltup/rn-fetch-blob#user-content-upload-example--dropbox-files-upload-api
完整步骤如下:
1.选取照片
//弹出选择相册和拍照的选项
showCameraSheet = () => {
requestPermission(PermissionsAndroid.PERMISSIONS.CAMERA, () => {
this.cameraConfigure();
}, () => {
this.cameraConfigure();
});
};
注意,安卓需要获取权限,iOS 需要在 plist 文件中加对应权限
WX20190420-111951.png
安卓获取权限代码
//请求安卓系统相应权限
export function requestPermission(androidPermissionName, callBack, iosCallBack) {
if (!IS_IOS) {
PermissionsAndroid.request(androidPermissionName).then((response) => {
if (response === PermissionsAndroid.RESULTS.GRANTED) {
callBack && callBack();
}
})
} else {
iosCallBack && iosCallBack();
}
}
2.获取选取的图片的相关信息
cameraConfigure = () => {
const options = {
title: '从相册选择或拍摄',
chooseFromLibraryButtonTitle: '从相册选择',
takePhotoButtonTitle: '拍摄',
cancelButtonTitle: '取消',
storageOptions: {
skipBackup: true,
},
};
ImagePicker.showImagePicker(options, (response) => {
if (!response.error) {
if (response.didCancel) {
return;
}
const source = {uri: response.uri};
this.base64 = response.data;
//注意,iOS 获取的图片地址要替换掉"file://",这是后面上传遇到的坑
this.fileURI = IS_IOS ? response.uri.replace('file://', '') : response.uri;
this.fileName = response.fileName || 'cash.jpg';
this.fileType = response.type;
this.setState({
uploadImage: source,
showUploadIcon: false,
})
}
});
};
3.准备上传
//FILE_SERVER为文件上传服务器地址
RNFetchBlob.fetch('POST', FILE_SERVER + 'upload/tspResource', {
'Content-Type': 'multipart/form-data',
}, [
{ name: this.fileName, filename: this.fileName, type: 'image/jpeg', data: RNFetchBlob.wrap(this.fileURI) }
]).then((response) => {
return response.text();
})
4.不出意外的话,上传结束。拿到服务器返回的数据进行处理
网友评论