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')
                    }
                })
            }
        }
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章