react-native-image-picker
imagePicker() {
let that = this;
const options = {
title: '选择一张图片',
cancelButtonTitle: '取消',
takePhotoButtonTitle: '拍照',
chooseFromLibraryButtonTitle: '从相册中选择',
quality: 1.0,
maxWidth: 500,
maxHeight: 500,
storageOptions: {
skipBackup: true
}
};
ImagePicker.showImagePicker(options, (response)=> {
if (response.didCancel) {
}
else if (response.error) {
}
else if (response.customButton) {
}
else {
let source;
let imageName;
let imagePath;
if (Platform.OS === 'android') {
source = response.uri;
imagePath = response.path;
imageName = response.fileName;
} else {
//{"uri":"/var/mobile/Containers/Data/Application/CC01D123-59FA-4205-8B27-C3181596AA5C/Documents/6131CE7A-FD8C-44DB-B9B9-82C322294B88.jpg","isStatic":true}
//file:///Users/dev/Library/Developer/CoreSimulator/Devices/DA8C975D-D476-462B-B387-D43FBC55C333/data/Containers/Data/Application/6231A942-22AA-40DC-A303-898EDE2C7533/Documents/2E98BCB0-8A9E-43FF-88E6-E7BE2094EE62.jpg
source = response.uri.replace('file://', '');
imagePath = response.uri.replace('file://', '');
imageName = that.getImageNameByIOS(response.uri);
}
let imageinfo = [];
imageinfo['uri'] = source;//这个是给React-native Image组件显示图片用得地址;
imageinfo['imageName'] = imageName;//图片名称
imageinfo['imagePath'] = imagePath;//图片在本机的路径.
that.setState({
default_image: imageinfo,
});
}
})
}
react-native-image-crop-picker
/**图片上传开始**/
import ActionSheet from "react-native-actionsheet";
import ImagePicker from "react-native-image-crop-picker";
import MyStroage from '../../common/myStroage';
import Util from '../../common/util' //--工具
import * as URLconstant from '../../constant/URLconstant' // --接口
constructor(props) {
super(props);
this.arrImg = []
this.state = {
photos:[],
};
}
requestPermission = async () => {
try {
const granted = await PermissionsAndroid.request(
PermissionsAndroid.PERMISSIONS.WRITE_EXTERNAL_STORAGE,
{
title: '申请读写手机存储权限',
message:
'一个很牛逼的应用想借用你的摄像头,' +
'然后你就可以拍出酷炫的皂片啦。',
buttonNeutral: '等会再问我',
buttonNegative: '不行',
buttonPositive: '好吧',
},
);
if (granted === PermissionsAndroid.RESULTS.GRANTED) {
console.log('现在你获得摄像头权限了');
} else {
console.log('用户并不给你');
}
} catch (err) {
console.warn(err);
}
};
//吊起选择框
async _imagePicker(isMultiple){
await this.requestPermission();
let newPhotos = this.state.photos
this.setState({
isMultiple:isMultiple
})
if(newPhotos.length>=6){
Toast.show("图片最多为6张")
return
}
this.ActionSheet.show()
}
//相册选择
selectFromAlbum(){
console.warn('您选择的是相册')
let isMultiple = this.state.isMultiple
ImagePicker.openPicker({
multiple: isMultiple
}).then(photos => {
console.warn('选中的图片===',photos);
this.setState({
isLoading:true
})
if(isMultiple){ //true 为多选
let arr = this.state.photos
photos.map((item,id)=>{
console.warn('选中的图片item===',item);
arr.push(item)
this.uploadImage(item.path)
})
console.warn('选中的图片arr===',arr)
this.setState({
photos:arr
})
}else{
this.uploadImage(photos.path)
this.setState({
headerImg:photos
})
}
}).catch((e)=>{
console.warn("取消选择",e)
});
}
//相机拍摄
selectphotograph(){
console.warn('选择的是相机拍摄')
let newPhotos = this.state.photos
let isMultiple = this.state.isMultiple
if(newPhotos.length===3){
alert("图片最多为3张")
return
}
ImagePicker.openCamera({
width: 300,
height: 400,
cropping: true,
}).then(photos => {
console.log(photos);
if(isMultiple) { //true 为多选
let arr = newPhotos.concat(photos)
this.setState({
photos: arr,
// imgNameArr:imageArr
});
let newArr = this.state.photos
console.warn('newPhotosArr==',newArr,'newPhotosArr.length===',newArr.length)
this.uploadImage(photos.path,newArr.length)
}else{
this.setState({
headerImg:photos
})
}
});
}
//上传图片到阿里云
uploadImage(sourceUri,length) {
console.log('sourceUri===',sourceUri)
let url = URLconstant.UPLOAD_IMAGE
let datakey = []
let upload_photo = {
uri: sourceUri, //本地路径
type: "multipart/form-data",
name: this.backName(sourceUri)
}
datakey['image_file_storeImageUpload'] = upload_photo
let isMultiple = this.state.isMultiple
Util.post(url, datakey, (datas) => {
// LOG('res===多张图片上传到阿里云成功' + JSON.stringify(datas))
if (datas.status == 0) {
if(isMultiple){ //true为多选
this.arrImg.push(datas.data.image_url)
}else{
this.headImg = datas.data.image_url
}
console.warn('最终的上传完成的图片数组===',this.arrImg)
setTimeout(()=>{
this.setState({
isLoading:false
})
},1000)
this.saveImageWithTag(datas.data.image_url)
} else {
Toast.show(datas.msg)
}
}, (err) => {
LOG(err)
})
}
backName(res) {
// LOG('res===多张图片上传到阿里云' + res)
return res.split('/').pop()
}
saveImageWithTag(uri) {
if (Platform.OS === 'android') {
// SaveModule.initSave(uri);
} else {
CameraRoll.saveToCameraRoll(uri, 'photo').done(function (data) {
LOG("保存图片成功 data==" + data);
Toast.show("保存图片成功", 2);
}, function (err) {
LOG("保存图片失败 err==" + err);
Toast.show("保存图片失败", 2);
});
}
}
deletePhotos(item,id){
let photos = this.state.photos
// console.log('删除照片',item)
// console.log('this.arrImg==',this.arrImg)
this.arrImg.splice(id,1)
photos.splice(id,1)
// console.log('this.arrImg1==',this.arrImg)
this.setState({
photos:photos,
})
}
/**图片上传结束**/
<View style={{flexDirection:'row',flexWrap:'wrap'}}>
{
this.state.photos.map((item, index) => {
let source = {uri: item.path};
if (item.enableBase64) {
source = {uri: item.base64};
}
return (
<View key={index} style={{
width:Util.size.width/8,
height:Util.size.width/8,
marginTop:(Util.size.width-(Util.size.width/3.2)*3)/3-14,
marginRight:(Util.size.width-(Util.size.width/3.2)*3)/3-14,
position:'relative'
}}>
<TouchableOpacity
onPress={()=>this.deletePhotos(item,index)}
activeOpacity={1}
style={{width:18,height:18,borderRadius:999,backgroundColor:'#ddd',position:'absolute',zIndex:1,right:-4,top:-10,justifyContent:'center',alignItems:'center'}}>
<Text style={{fontSize:15,top:-1}}>×</Text>
</TouchableOpacity>
<Image
key={`image-${index}`}
style={{width:'100%',height:'100%',borderRadius:5,}}
source={source}
resizeMode={'cover'}
/>
</View>
);
})
}
<TouchableOpacity onPress={()=>this._imagePicker(true)} style={{
height: Util.size.width/8,
width:Util.size.width/8,
justifyContent:'center',alignItems:'center', backgroundColor: '#F5F6FC',
marginTop:(Util.size.width-(Util.size.width/3.2)*3)/3-14,
marginRight:(Util.size.width-(Util.size.width/3.2)*3)/3-14,
borderRadius: 10 }}>
<Text style={{fontSize:50,fontWeight:'bold',color:'#C7C8D3'}}>+</Text>
</TouchableOpacity>
</View>
{/*图片选择*/}
<ActionSheet
ref={o => this.ActionSheet = o}
title={'请选择照片类型'}
options={['选择相册', '相机', '取消']}
cancelButtonIndex={2}
destructiveButtonIndex={1}
onPress={(index) => { if(index===0){this.selectFromAlbum()}else if(index===1){this.selectphotograph()} }}
/>
POST 提交图片
//多图以 xxx.jpg,xxx.jpg,xxx.jpg拼接
//图片
let imgNameArr = this.arrImg
let imgStr = ''
imgNameArr.map((item,id)=>{
id > 0 ? imgStr += ',' + item : imgStr = item
})
网友评论