004-React-Native--多圖選擇上傳

來源:互聯網
上載者:User

標籤:conf   extend   require   hid   res   loading   als   auto   pos   

參考資料:http://www.jianshu.com/p/488e62ed9656

 

一:使用react-native-image-crop-picker進行圖片選擇時,並沒有提供多圖的機制。
當你從相機選擇圖片時,會覆蓋之前已經存在的圖片。所以,今天,來一個多圖選擇並上傳的例子,此例子中,會儲存你之前已經選擇的圖片。例如,當前列表已經存在一張照片,當你去相簿或者使用相機進行拍照時,不會覆蓋當前列表已經存在的照片。

二:使用FormData進行圖片上傳,並根據需要進行其他參數的添加

三: Coding


pic.gif
//第三方庫,需要使用npm引入import ImagePicker from ‘react-native-image-crop-picker‘;import ActionSheet from ‘../../components/ActionSheet/ActionSheet‘import Config from ‘../../../Config‘import ModalProgress from ‘../../components/Progress/ModalProgress‘//存放數組var dataToPost = [];export  default class LoadingPage extends React.Component {    static navigationOptions = ({ navigation }) => {        const {state} = navigation;        return {            title: ‘上傳資訊‘,            headerRight: (                <Button                    title="上傳"                    onPress={()=>{                      state.params.commitPage();                    }}                />            ),        };    };    componentWillMount(){        this.props.navigation.setParams({            commitPage:this.commitPage,        })    }    constructor(props){        super(props);        this.state={            images: [],        }    }    show() {        let items = [            {title: ‘從相簿選取‘, onPress: () => this.openPicLib()},            {title: ‘拍照一張‘,onPress: () => this.pickSingleWithCamera()},        ];        let cancelItem = {title: ‘關閉‘};        ActionSheet.show(items, cancelItem);    }    render(){        return(            <ScrollView>                <View>                    <View>                        <View style={styles.viewPadding}>                            {this.createImageItem()}                        </View>                    </View>                    <View style={styles.itemLine}/>                </View>            </ScrollView>        )    }    createImageItem(){        let  imageSource = require(‘../../imgs/upload.png‘);        let mainView;        if(this.state.images!=null&&this.state.images.length>=9){            mainView=null;        }else{            mainView=  <TouchableOpacity                onPress={()=>{                    this.show();                }}>                <Image source={imageSource} />            </TouchableOpacity>        }        return(            <View>                <View>                    {this.state.images ? this.state.images.map(i => <View key={i.uri}>{this.renderImage(i)}</View>) : null}                </View>                <View>                    {mainView}                </View>            </View>        )    }   //從相機擷取圖片    pickSingleWithCamera=()=> {        ImagePicker.openCamera({            cropping: false,            width: Math.round((Dimensions.get(‘window‘).width-20)),            height: 300,        }).then(image => {            dataToPost.push({                uri: image.path,                width: image.width,                height: image.height,            });            this.setState({                images: dataToPost            });        }).catch(            e => alert(e)        );    }//從圖庫或者相機進行擷取,因為安卓平台不能進行多圖選擇,所以,需要區分不同平台    openPicLib=()=> {        if(Platform.OS === ‘ios‘){            ImagePicker.openPicker({                multiple: true,                waitAnimationEnd: false,            }).then(images => {                for (var i=0;i<images.length;i++) {                    dataToPost.push({                        uri: images[i].path,                        width: images[i].width,                        height: images[i].height,                        mime: images[i].mime,                    });                }                this.setState({                    images: dataToPost                });            }).catch(e =>                alert(e)            );        }else{            ImagePicker.openPicker({                width: 300,                height: 300,                cropping: false,                cropperCircleOverlay: false,                compressImageMaxWidth: 480,                compressImageMaxHeight: 640,                compressImageQuality: 0.5,                mediaType: ‘photo‘,                compressVideoPreset: ‘MediumQuality‘            }).then(image => {                dataToPost.push({                    uri: image.path,                    width: image.width,                    height: image.height,                    mime: image.mime                });                this.setState({                    images: dataToPost                });            }).catch(e => {                Alert.alert(e.message                    ? e.message                    : e);            });        }    }    renderImage(image) {        return <Image style={{width: 100, height: 100, resizeMode: ‘contain‘}} source={image} />    }   //資料提交    commitPage=()=>{        let formData = new FormData();        if(this.state.images == null){            alert("沒有選擇圖片");        } else {            for(var i = 0;i<this.state.images.length;i++){                var uri = this.state.images[i].uri;                var index = uri.lastIndexOf("\/");                var name  = uri.substring(index + 1, uri.length);                let file = {uri: uri, type: ‘multipart/form-data‘, name: name } ;                formData.append(‘file‘, file);            }        }        //上傳圖片時,可以在此添加相關其他參數        formData.append(‘userId‘, ‘1‘);        formData.append(‘fileType‘, ‘image‘);        formData.append(‘name‘,‘time‘);        formData.append(‘phone‘, ‘11222222‘);        ModalProgress.show("資料上傳中,請稍後....");        const REQUEST_URL = Config.domain+‘/upload/uploadQualifications‘;        fetch(REQUEST_URL,{            method:‘POST‘,            headers:{                ‘Content-Type‘:‘multipart/form-data‘,                ‘Accept‘: ‘application/json‘            },            body:formData,        }).then((response) => response.json()).then((responseJson) => {            alert(JSON.stringify(responseJson));            if (responseJson.status == 0) {                ModalProgress.hide();                {this.goBack()}            }else{                ModalProgress.hide();                alert(responseJson.msg);            }        }).catch((error) => {            alert(error);            ModalProgress.hide();        });    }}

 

 

image.png

Time_二胡

著作權歸作者所有。商業轉載請聯絡作者獲得授權,非商業轉載請註明出處。

 

 

004-React-Native--多圖選擇上傳

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.