当前位置: 首页>数据库>正文

react-native-syan-image-picker同时上传多张图片(Android))

第三方库的链接:https://github.com/syanbo/react-native-syan-image-picker
因为之前用的是react-native-image-picker,但是选择多张图片这里因为不是很懂,所以找了个更加方便的选择多张图片的第三方库,还可以裁剪
一、安装

yarn add react-native-syan-image-picker
react-native link react-native-syan-image-picker

二、在 AndroidManifest.xml 中添加权限:

<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.CAMERA" />

三、android/build.gradle 查看是否是minSdkVersion = 19,不是则改

四、然后配置暂且到此为止,使用的官网demo在此链接:https://github.com/syanbo/RNPlayground/blob/master/src/screen/ImagePicker/index.js

因为yarn add react-native-syan-image-picker直接点击就是直接调用相机或者相册,没有弹出说选择相机还是相册,所以有需要的可以安装另外一个第三方库配合:https://github.com/beefe/react-native-actionsheet,安装使用极其方便,下面附上我的使用例子

//意见反馈
'use strict';
import React,{Component} from 'react';
import styles from '../style/styles';
import Header from '../common/header';
import ImagePicker from 'react-native-image-picker';
import Icon from 'react-native-vector-icons/Ionicons';
import * as URLconstant from '../constant/URLconstant';
import SYImagePicker from 'react-native-syan-image-picker';
import ActionSheet from 'react-native-actionsheet'
import Util from '../common/util'
import Toast from '../common/ToastUtil'
import {
    View,
    Text,
    Image,
    TouchableOpacity,
    ScrollView,
    TextInput,
    Platform, ImageBackground, StyleSheet,
    PermissionsAndroid
} from 'react-native';
import storage from "../common/storage";
export default class commentOrder extends Component{
    // 构造
      constructor(props) {
        super(props);
        // 初始状态
        //   this.imagePicker=this.imagePicker.bind(this)
        this.state = {
            photos:[],
            starNum:5,
            uploadImgNum:3,
            order_id:this.props.order_id,
            goods_id:this.props.goods_id,
            goods_image:this.props.goods_image,
            user_id:this.props.user_id,
            problem:'',
            imgNameArr:[]
        };
      }

      componentDidMount() {
      }

    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);
        }
    };

    // getImageNameByIOS(imageUri) {
    //     if (imageUri != "") {
    //         var names = imageUri.split("/");
    //         return names[names.length - 1];
    //     }
    // }

    //选择图片

    // imagePicker(i){
    //     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;
    //             let imageArr = this.state.imgNameArr
    //
    //             if (Platform.OS === 'android') {
    //                 source = response.uri;
    //                 imagePath = response.path;
    //                 imageName = response.fileName;
    //                 imageArr.push(response.fileName)
    //                 // console.warn('图片名字===',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);
    //             }
    //             // console.warn('图片数组======',imageArr)
    //
    //             let imageinfo = [];
    //             let imgUri = 'imgUri'+i;
    //             imageinfo['uri'] = source;//这个是给React-native Image组件显示图片用得地址;
    //             imageinfo['imageName'] = imageName;//图片名称
    //             imageinfo['imagePath'] = imagePath;//图片在本机的路径.
    //             that.setState({
    //                 [imgUri]: imageinfo,
    //                 default_image: imageinfo,
    //             });
    //         }
    //     })
    // }

    //吊起选择框
    async _imagePicker(){
        this.ActionSheet.show()
    }

    //相册选择
    selectFromAlbum(){
        // console.warn('您选择的是相册')
        SYImagePicker.asyncShowImagePicker({imageCount: 3})
            .then(photos => {
                const arr = photos.map(v => {
                    return v;
                });
                // 选择成功
                console.warn('选择成功',arr);
                this.setState({
                    photos: arr,
                });
            })
            .catch(err => {
                // 取消选择,err.message为"取消"
            });
    }

    //相机拍摄
    selectphotograph(){
        // console.warn('选择的是相机拍摄')
         this.requestPermission();  //吊起相机时访问权限
        SYImagePicker.openCamera(
            {isCrop: false, showCropCircle: false, showCropFrame: false},
            (err, photos) => {
                console.warn(err, photos);
                // if (!err) {
                //     this.setState({
                //         photos: [...this.state.photos, ...photos],
                //     });
                // }
            },
        );
    }

    //提交反馈
    SubmitFeed() {
          // console.warn('提交反馈')
        // console.warn('是否有图片,====',this.state.photos)

        let imgNameArr = this.state.imgNameArr
        let str = ''
        imgNameArr.map((item)=>{
             str += item + ','
        })
        // console.warn(str)

        storage.load({
            key: 'userinfo',
            autoSync: true,
            syncInBackground: true,
            syncParams: {
                extraFetchOptions: {
                },
                someFlag: true
            }
        }).then(res => {
            // console.warn('ISLOGIN===',res)
            console.warn('res.key===',res.data.key)
            console.warn('res.user_id===',res.data.user_id)
            // console.warn('deviceName===',item.name)
            // console.warn('mac===',item.id)
            // console.warn('跳转item==================',item)
            let userLoginUrl = URLconstant.USER_SUGGEST_URL;
            let userData = []
            userData['user_id'] = res.data.user_id
            userData['deviceName'] = 'JGDY-01'
            userData['problem'] = this.state.problem
            userData['proof_img'] = str

            Util.post(userLoginUrl, userData,  (datas)=>{
                let data = JSON.stringify(datas)
                Toast.show(JSON.parse(data))
                LOG('提交反馈成功===',data)
            }, this.errorcallback);

        })

    }
    errorcallback(){
        Toast.show('提交失败')
          console.warn('提交失败')
    }

    uploadImg(){
        let that = this;
        let uploadImgNum = that.state.uploadImgNum;

        let rows;
        let list=[];
        for(let i =1;i<=uploadImgNum;i++){
            //LOG('state==='+JSON.stringify(this.state))
            let imgUri='imgUri'+i;
            let imgUriList = that.state[imgUri]
            let uri;
            if(imgUriList!=null){
                uri=imgUriList['uri'];
            }

            rows=(
                <TouchableOpacity style={styles.comment_used_wrap} onPress={()=>this.imagePicker(i)} key={i}>
                    <Icon name={'md-images'} size={70} color={'#aaa'}/>
                    <Image
                        resizeMode="cover"
                        style={styles.comment_used_img}
                        source={{uri:uri}}/>
                </TouchableOpacity>
            )
            list.push(rows)
        }
        return list;
    }

    render(){
        let user_id = this.props.user_id;
        let photos = this.state.photos
        return(
            <View style={{flex:1}}>
                <ImageBackground style={{ flex: 1 }}
                                 source={require('../imgs/common/bg.png')}>
                <Header navigation={this.props.navigation}  initObj={{title:'Feedback', id:2, bgColor:'transparent', fontColor: '#fff'}}/>
                <ActionSheet
                    ref={o => this.ActionSheet = o}
                    title={'请选择照片类型'}
                    options={['选择相册', '相机', '取消']}
                    cancelButtonIndex={2}
                    destructiveButtonIndex={1}
                    onPress={(index) => { if(index===0){this.selectFromAlbum()}else{this.selectphotograph()} }}
                />
                <View style={{paddingHorizontal:10}}>
                    <View style={{height:180,width:'100%', alignItems:'center'}}>
                        {/*<View style={{height:'100%'}}></View>*/}
                        <ImageBackground style={{
                            flex:1,
                            height:160,
                            alignItems:'center',marginTop:10,
                            }} source={require('../imgs/common/feedbackBg.png')}>
                            <TextInput
                                style={style.mycomment}
                                placeholder={'Please enter feedback...'}
                                placeholderTextColor="#fff"
                                multiline={true}
                                underlineColorAndroid={'transparent'}
                                clearButtonMode={'always'}
                                onChangeText={(text)=>this.setState({problem:text})}
                            />
                        </ImageBackground>
                    </View>
                    {/*<View style={styles.comment_upload_wrap}>*/}
                    {/*    {this.uploadImg()}*/}
                    {/*</View>*/}
                    <View style={{flexDirection:'row'}}>
                        {
                            photos.map((item, index) => {
                            let source = {uri: item.uri};
                            if (item.enableBase64) {
                                source = {uri: item.base64};
                            }
                            return (
                                    <Image
                                        key={`image-${index}`}
                                        style={{width:100,height:100,marginLeft: 10}}
                                        source={source}
                                        resizeMode={'contain'}
                                    />
                                );
                            })
                        }
                    </View>


                    <TouchableOpacity style={{alignItems:'center',marginTop:61}} onPress={()=>this._imagePicker()}>
                        <Image source={require('../imgs/add.png')} style={{height:32.5,width:32.5}}/>
                    </TouchableOpacity>


                    <View style={styles.comment_submit_wrap} >

                        <TouchableOpacity style={{
                            height:45,
                            margin:10}} onPress={()=>this.SubmitFeed()}>
                            <ImageBackground style={{
                                flex:1,width:324.5,
                                height:53, alignItems:'center',
                                justifyContent:'center'}} source={require('../imgs/common/add_device_bg.png')}>
                                <Text style={{textAlign:'center', justifyContent: 'center', color:'#fff'}}>Submit</Text>
                            </ImageBackground>
                        </TouchableOpacity>
                    </View>
                </View>

                </ImageBackground>
            </View>
        )
    }
}
const style = StyleSheet.create({
    mycomment:{
        width:Util.size.width-30,
        height:160,
        // backgroundColor:"#f0f0f0",
        // borderWidth:1,
        // borderColor:"#ccc",
        marginLeft:10,
        textAlignVertical:'top',
        fontSize:12,
        color:'#fff'
    },
    image: {
        margin: 10,
        width: (Util.size.width - 80) / 3,
        height: (Util.size.width - 80) / 3,
        backgroundColor: '#F0F0F0',
    },
})

https://www.xamrdz.com/database/6ga1994528.html

相关文章: