RN6.0以后版本的照片上传
很久没写RN了,公司需求,废话不多说,直接上代码
首先,照片选择器 yarn add react-native-image-picker
android目录下的settings.gradle
include ':react-native-image-picker'
project(':react-native-image-picker').projectDir = new File(rootProject.projectDir, '../node_modules/react-native-image-picker/android')
android/app 下的 build.gradle 添加
dependencies{
...
api project(':react-native-image-picker')
.....
}
之后在AndroidManifest.xml配置相机权限
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
再在MainApplication.java中配置
import com.imagepicker.ImagePickerPackage;
最后拍照上传
引入 import ImagePicker from 'react-native-image-picker';
this.state={
fileData: '',
}
//照片选择器,可拍照,可在相册选择
selectPhotoTapped() {
var options = {
quality: 1.0,
maxWidth: 500,
maxHeight: 500,
title: '请选择图片来源',
cancelButtonTitle: '取消',
takePhotoButtonTitle: '拍照',
chooseFromLibraryButtonTitle: '相册图片',
storageOptions: {
skipBackup: true,
path: 'images'
}
};
ImagePicker.showImagePicker(options, response => {
//console.log('Response = ', response);
let fileData = this.state.fileData;
fileData = response;
this.setState({
fileData,
});
console.log("fileData===================================>>>>"+this.state.fileData)
if (response.didCancel) {
//console.log('response='+response);
} else if (response.error) {
console.log('ImagePicker Error: ', response.error);
} else if (response.customButton) {
console.log('User tapped custom button: ', response.customButton);
} else {
let source = {uri: response.uri};
this.setState({
avatarSource: source,
});
}
});
}
//上传照片的方法
fetch(uploadURL,{
method:'POST',
headers:{
'Content-Type':'multipart/form-data',
},
body:formData,
})
.then((response) =>response.text() )
.then((responseData)=>{
console.log('responseData',responseData);
})
.catch((error)=>{console.error('error',error)});
<View style={styles.container}>
<TouchableOpacity onPress={this.selectPhotoTapped.bind(this)}>
<View
style={[styles.avatar, styles.avatarContainer, {marginBottom: 20}]}>
{this.state.avatarSource === null ? (
<Text>选择照片</Text>
) : (
<Image style={styles.avatar} source={this.state.avatarSource} />
)}
</View>
</TouchableOpacity>
</View>
全是干货,用完觉得有用的给个好评