ReactNative-第三方-react-native-image-picker 选择图片上传

可以设置直接访问相机、相册,也可以弹出选择框进行选择

    choosePicker = () => {
        const photoOptions = {
            title: "请选择",
            quality: 0.8,
            cancelButtonTitle: "取消",
            takePhotoButtonTitle: "拍照",
            chooseFromLibraryButtonTitle: "选择相册",
            allowsEditing: true,
            noData: false,
            storageOptions: {
                skipBackup: true,
                path: "images"
            }
        };
        ImagePicker.showImagePicker(photoOptions, response => {
            console.log("Response = ", response);
            const { avatarSource, imgAry } = this.state;
            console.log(avatarSource);
            if (response.didCancel) {
                return;
            } else if (response.error) {
                console.log("ImagePicker Error: ", response.error);
            } else if (response.customButton) {
                console.log("User tapped custom button: ", response.customButton);
            } else {
                let source;
                source = {uri: 'data:image/jpeg;base64,' + response.data};
                if (Platform.OS === 'android') {
                    source = { uri: response.uri };
                } else {
                    source = { uri: response.uri.replace('file://','') };
                }
                avatarSource.push(source);
                imgAry.push({uri: response.uri, type: 'multipart/form-data', name: response.fileName});
                this.setState({
                    avatarSource,
                    imgAry
                });

            }
        });
    };

选择后的图片信息

处理上传数据,单张图片

 let fd = new FormData();//如果需要上传多张图片,需要遍历数组,把图片的路径数组放入formData中
 let file = {uri: response.uri, type: 'multipart/form-data', name:response.name}; //这里的key(uri和type和name)不能改变,
 fd.append("file",file); //这里的file就是后台需要的key

多张图片上传

 let fd = new FormData(); 
   for(var i = 0;i<imgAry.length;i++){ 
        fd.append("file",imgAry[i]); 
} 

使用axios上传

需配置headers

axios.defaults.headers.common['Content-Type'] = 'multipart/form-data';

react-native-image-picker

npm i react-native-image-picker 或 yarn add react-native-image-picker
打赏

共有 0 条评论

Top