zoukankan      html  css  js  c++  java
  • 004-React-Native--多图选择上传



    参考资料: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,
                 Math.round((Dimensions.get('window').width-20)),
                height: 300,
            }).then(image => {
                dataToPost.push({
                    uri: image.path,
                     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,
                             images[i].width,
                            height: images[i].height,
                            mime: images[i].mime,
                        });
                    }
                    this.setState({
                        images: dataToPost
                    });
                }).catch(e =>
                    alert(e)
                );
    
            }else{
                ImagePicker.openPicker({
                     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,
                         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={{ 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_二胡

    著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
  • 相关阅读:
    Python开发入门与实战16-APACHE部署
    Python开发入门与实战15-IIS部署
    Python开发入门与实战14-基于Extjs的界面
    团队作业4:第三篇Scrum冲刺博客(歪瑞古德小队)
    团队作业4:第二篇Scrum冲刺博客(歪瑞古德小队)
    团队作业4:第一篇Scrum冲刺博客(歪瑞古德小队)
    团队作业4:项目冲刺集合贴(歪瑞古德小队)
    团队作业3:需求改进&系统设计(歪瑞古德小队)
    团队作业2:需求规格说明书(歪瑞古德小队)
    使用docker安装codimd,搭建你自己的在线协作markdown编辑器
  • 原文地址:https://www.cnblogs.com/gdsblog/p/7279435.html
Copyright © 2011-2022 走看看