在React Native中使用axios,formdata和react-native-image-crop-picker上传图像

时间:2020-05-05 07:35:14

标签: file-upload axios

我想上传一张照片,为此,我已经安装了提到的软件包并试图实现这一目标。 *我尝试过Fetch,也尝试过fetch-blob,但没有锁定 *开始时catch错误是网络错误 现在的问题是我正在向服务器发送一个空数组 这是我的代码:

export default class Upload extends Component {
    constructor() {
        super();
        this.state = {
            token: "",
            photos: []
        }
    }
    render() {
        return (
            <Text onPress={() => this._TakePhoto()}> Pick </Text>
        );
    }
    _TakePhoto() {
        ImagePicker.openPicker({
            multiple: true
        }).then(images => {
            images.map((item, index) => {
                ImageResizer.createResizedImage(item.path, 1200, 1200, "JPEG", 100)
                    .then(response => {
                        // console.warn('Resized img is: ', response);
                        this.state.photos.push(response);
                        console.warn('Resized img state is: ',  this.state.photos)
                        this._submit_pictures()

                    })
                    .catch(err => {
                    });
            });

        });

    }

    _submit_pictures() {
        let formData = new FormData();
        for (let i = 0; i < this.state.photos.length; i++) {
            let file = {
                uri: this.state.photos[0].path,
                // uri: this.state.photos[0].path.replace('file:///', ''),
                // uri: this.state.photos[0].uri,
                type: this.state.photos[0].mime,
                name: this.state.photos[0].name
            };
            formData.append("pics[]", file);
        }
        //     uri: this.state.photos[0].uri.replace("file:///", "file://"),
        formData.append("postId", postId);
        formData.append("token", token);
        console.log('formData value: ', formData)
            axios({
                url: "https://rahnama.com/webservice/submitPictures",
                method: "POST",
                headers: {
                    // "Accept": "application/json",
                    "Content-Type": "multipart/form-data"
                },
                // formData
                body: formData
            })
            .then(response => {
                console.warn('upload res: ', response);
            }).catch((error) => console.warn('upload err: ', error.response.request._response));
    }
}

1 个答案:

答案 0 :(得分:1)

我通过将数据作为 base64(图像)发送来解决了这个问题