react native 使用ImageCropPicker 七牛云上传图片

React Native 版本执行0.57的规则

import React, { Component } from 'react';
import { StyleSheet, Text, View, ScrollView, Image, KeyboardAvoidingView, TouchableOpacity, StatusBar, TextInput } from 'react-native';
import Nav from '../../components/Nav';
import { requestUrl } from '../../network/Url';// 请求url
import Fetch from '../../network/Fetch';
import { global } from '../../utils/Global';
import GetImages from '../../components/ImageCropPicker';//打开相机
import Loading from '../../components/Loading';
import { CachedImage } from "react-native-img-cache";

const imag = 'http://appimg.wangjushijie.com/'

export default class App extends Component {
    constructor(props) {
        super(props);
        this.state = {
            isGetImages: false,//相机开关
            isLoading: false,
            imgIndex: 0,//传递成功照片的张数
            pinLun: '',//评论内容
            pinImage: [],//评论图片资源
            urlImgArr: [],// 七牛返回的图片路径数组
            subFlag: false,
            shopArr: {}
        }
    }
    componentWillMount() {
        //接受一级页面数据
        if (this.props.navigation.state.params) {
            this.setState({
                shopArr: this.props.navigation.state.params.orderArr
            })
        }
    }
    componentDidMount() {
        if (this.state.shopArr) {
            this._getOrderDeatil2(this.state.shopArr)
        }
    }
    //获取待评价订单号
    _getOrderDeatil2(item) {
        this.setState({
            isLoading: true,
        })
        Fetch(requestUrl.getOrderDeatil2, {
            'userId': UserInfo.id,
            'orderId': item.id,
            'goodsId': item.goods_id
        }).then(data => {
            if (data.status == 'SUCCESS') {
                this.setState({
                    isLoading: false,
                    orderid: data.data[0].orderId
                })
            }
        })
    }
    render() {
        const { navigate, goBack } = this.props.navigation;
        return (
            <KeyboardAvoidingView
                behavior={IOS ? "padding" : null}
                style={styles.container}
            >
                <StatusBar
                    animated={true}//是否动画
                    hidden={false}//是否隐藏
                    backgroundColor={'#000'}//android 设置状态栏背景颜色
                    translucent={false}//android 设置状态栏是否为透明
                    showHideTransition="fade"//IOS状态栏改变时动画 fade:默认 slide
                    networkActivityIndicatorVisible={this.state.isLoading}//IOS设定网络活动指示器(就是那个菊花)是否显示在状态栏。
                    statusBarStyle={"default"}//状态栏样式 default	默认(IOS为白底黑字、Android为黑底白字)
                    barStyle={"default"}// 状态栏文本的颜色。
                />
                <Nav title={"评价"} leftClick={() => { goBack() }} />
                <View style={styles.topView}>
                    <ScrollView>
                        <View style={styles.bomView}>
                            <Text style={{ fontSize: Px2dp(14), color: Colors.text666, marginBottom: Px2dp(8), lineHeight: Px2dp(20) }}>1、请您写下宝贵的意见,帮助其他小伙伴完成放心的购买;</Text>
                            <Text style={{ fontSize: Px2dp(14), color: Colors.text666, lineHeight: Px2dp(20), marginTop: Px2dp(8) }}>2、我们将对最最最用心的用户奉上我们的优惠券。</Text>
                        </View>
                        <View style={{ height: Px2dp(10), backgroundColor: Colors.mainBg }}></View>
                        <View style={[styles.bomView, { marginTop: 0 }]}>
                            <View style={styles.alignTxt}>
                                <CachedImage style={{ width: Px2dp(50), height: Px2dp(50), marginRight: Px2dp(8) }} source={{ uri: this.state.shopArr && this.state.shopArr.list_image }} />
                                <Text style={{ width: Px2dp(285), fontSize: Px2dp(14), color: '#333', lineHeight: Px2dp(20) }}>{this.state.shopArr && this.state.shopArr.goods_name}</Text>
                            </View>
                            <View style={styles.inputView}>
                                <TextInput
                                    maxLength={200}
                                    multiline={true}
                                    style={styles.TextView}
                                    placeholder='请写下您的使用心得,分享给想要购买的他们吧~'
                                    onChangeText={(text) => { this.setState({ pinLun: text }) }} />
                            </View>
                            {/* 评论字数展示 */}
                            <Text style={{ color: Colors.text666, marginTop: Px2dp(8), textAlign: 'right' }}>{this.state.pinLun.length}/200</Text>
                            {/* 评论图片展示 */}
                            <View style={{ flexDirection: 'row', flexWrap: 'wrap', marginTop: Px2dp(20) }}>
                                {this.state.pinImage.length > 0 && this.state.pinImage.map((item, index) => {
                                    return (
                                        <View key={index} style={styles.viewList}>
                                            {/* 删除按钮 */}
                                            <TouchableOpacity
                                                onPress={() => {
                                                    let pinImage = this.state.pinImage;
                                                    pinImage.splice(index, 1)
                                                    this.setState({
                                                        pinImage: pinImage
                                                    })
                                                }}
                                                style={[styles.viewPoimg, {
                                                    justifyContent: 'center',
                                                    alignItems: 'center'
                                                }]}
                                            >
                                                <Image source={require('../../images/deleteCopy.png')} />
                                            </TouchableOpacity>

                                            <Image style={{ width: Px2dp(70), height: Px2dp(70), }} source={{ uri: "data:image/jpeg;base64," + item.data }} />
                                        </View>
                                    )
                                })}
                                {/* 获取图片按钮 */}
                                {this.state.pinImage && this.state.pinImage.length > 5 ?
                                    null :
                                    <TouchableOpacity activeOpacity={.8}
                                        onPress={() => {
                                            this.setState({
                                                isGetImages: true
                                            })
                                        }}
                                        style={styles.viewList}>
                                        <Image source={require('../../images/Album.png')} />
                                        <Text style={{ fontSize: Px2dp(12), color: Colors.text999, marginTop: Px2dp(3) }}>{this.state.pinImage.length}/6</Text>
                                    </TouchableOpacity>
                                }
                            </View>
                        </View>
                    </ScrollView>
                </View>
                <TouchableOpacity activeOpacity={.8}
                    onPress={() => {
                        this.postAddComment()
                    }}
                    style={[styles.btnView, { marginBottom: TabBar }]}>
                    <Text style={{ fontSize: Px2dp(15), color: 'white' }}>提交评价</Text>
                </TouchableOpacity>

                {this.state.isGetImages ?
                    <GetImages
                        maxNum={6 - this.state.pinImage.length}
                        dataClick={(data) => {
                            // data  
                            // android 相机{} 相册[]
                            // {
                            //     data: "/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAAYEBQYFBAYGBQYHBw"
                            //     height: 1920
                            //     mime: "image/jpeg"
                            //     modificationDate: "1547631031000"
                            //     path: "file:///storage/emulated/0/Pictures/Screenshot_2019-01-16-17-30-30-1395852725-compressed.png"
                            //     size: 92044
                            //     width: 1080
                            // }
                            // IOS 相机
                            // {
                            //     creationDate: null
                            //     cropRect: null
                            //     data: "/9j/4AAQSkZJRgABAQAASABIAAD/4QBYRXhpZgAATU0AKgAAAA"
                            //     exif: null
                            //     filename: null
                            //     height: 720
                            //     localIdentifier: null
                            //     mime: "image/jpeg"
                            //     modificationDate: null
                            //     path: "/private/var/mobile/Containers/Data/Application/19A1B439-F744-4862-87C5-DC057253AAD9/tmp/react-native-image-crop-picker/044E034A-8302-40A6-BA35-3A827CCC0A6B.jpg"
                            //     size: 77113
                            //     sourceURL: null
                            //     width: 540
                            // }
                            // ios 相册
                            // {
                            //     creationDate: "1537232966"
                            //     cropRect: null
                            //     data: "/9j/4AAQSkZJRgABAQAASABIAAD/4QBYRXhpZgAATU0AKgAAAA"
                            //     exif: null
                            //     filename: "IMG_0997.JPG"
                            //     height: 720
                            //     localIdentifier: "8199879C-534C-4FE5-A845-F9BC922FBF37/L0/001"
                            //     mime: "image/jpeg"
                            //     modificationDate: "1549930194"
                            //     path: "/private/var/mobile/Containers/Data/Application/19A1B439-F744-4862-87C5-DC057253AAD9/tmp/react-native-image-crop-picker/E9927A02-BC4A-4D4B-8F61-27F4C59849E0.jpg"
                            //     size: 68611
                            //     sourceURL: "file:///var/mobile/Media/DCIM/100APPLE/IMG_0997.JPG"
                            //     width: 530
                            // }

                            // 获取到的数据
                            let pinImage = this.state.pinImage;
                            if (data instanceof Array) {
                                pinImage = pinImage.concat(data);
                            } else {
                                pinImage.push(data);
                            }
                            if (pinImage.length > 6) {
                                pinImage = pinImage.splice(pinImage.length - 6)
                            }
                            this.setState({
                                isGetImages: false,
                                pinImage: pinImage
                            })
                        }}
                        cancelClick={() => {
                            // 关闭事件
                            this.setState({
                                isGetImages: false
                            })
                        }}
                    />
                    : null
                }
                {this.state.isLoading ? <Loading /> : null}
            </KeyboardAvoidingView>
        );
    }
    // 添加评论信息
    postAddComment() {
        if (this.state.pinLun.length < 1) {
            ToastShow({ "text": "请输入评论文字" })
            return
        } else {
            this.setState({
                isLoading: true
            })
            // 图片处理
            let imgArr = this.state.pinImage;
            let _this = this;
            if (imgArr.length > 0) {
                for (let i = 0; i < imgArr.length; i++) {
                    // 创建图片路径
                    let _time = parseInt(new Date().getTime());
                    let suiji = Math.floor(Math.random() * 1000)
                    let year = new Date().getFullYear();
                    let month = new Date().getMonth() + 1;
                    let day = new Date().getDate();
                    let path = year + '/' + month + '/' + day + '/' + _time + suiji + imgArr[i].path.substr(imgArr[i].path.lastIndexOf("."));
                    let formData = new FormData();
                    formData.append("file", { uri: IOS ? "file://" + imgArr[i].path : imgArr[i].path, type: 'application/octet-stream', name: path });
                    Fetch(requestUrl.uptoken, { 'key': path }).then(data => {
                        formData.append("key", path);
                        formData.append("token", data.upToken);
                        fetch("https://upload.qiniup.com", {
                            method: 'POST',
                            headers: {},
                            body: formData,
                            contentType: false,
                            processData: false,
                        }).then((response) => response.json())
                            .then((responseData) => {
                                let temp = _this.state.urlImgArr;
                                temp.push(imag + responseData.key);
                                _this.setState({
                                    urlImgArr: temp,
                                });
                                if (temp.length >= imgArr.length) {
                                    Fetch(requestUrl.addComment, {
                                        'goodsId': _this.state.shopArr.goods_id,//商品ID
                                        'userId': UserInfo.id,//用户ID
                                        'text': _this.state.pinLun,//用户的评论文字
                                        'imagesUrls': _this.state.urlImgArr.join("|"),//用户的评论图片
                                        'orderId': _this.state.orderid,//订单ID
                                    }).then(data => {
                                        _this.setState({
                                            isLoading: false
                                        })
                                        if (data.status == 'SUCCESS') {
                                            _this.props.navigation.navigate('EvaluationSuccess')
                                        }
                                    })
                                }
                            })
                            .catch((error) => {
                                console.log('error', error);
                            });
                    })
                }
            } else {
                // 评论接口
                Fetch(requestUrl.addComment, {
                    'goodsId': this.state.shopArr.goods_id,//商品ID
                    'userId': UserInfo.id,//用户ID
                    'text': this.state.pinLun,//用户的评论文字
                    'imagesUrls': this.state.urlImgArr.join("|"),//用户的评论图片
                    'orderId': this.state.orderid,//订单ID
                }).then(data => {
                    this.setState({
                        isLoading: false
                    })
                    if (data.status == 'SUCCESS') {
                        this.props.navigation.navigate('EvaluationSuccess')
                    }
                })
            }
        }
    }
}

你可能感兴趣的:(React,Native,React编写原生应用,vuex)