简体   繁体   English

如何在 React Native 中上传图片

[英]How to upload an Image in React Native

I am trying to upload an image but I am failed because I am new to React Native .我正在尝试上传图片但我失败了,因为我是 React Native 的新手。 Actually, I want to select a photo then upload it to my server , from app it not working .实际上,我想选择一张照片,然后将它上传到我的服务器,从应用程序它不起作用。 when I give it try from postman it working .当我从邮递员那里尝试它时,它可以工作。 In postman I select form-data , In key I selected type as file when I hit on submit then image is successfully uploaded but when I try it from app it not working .在邮递员中,我选择了form-data ,在键中,当我点击提交时,我选择了类型作为file ,然后图像成功上传,但是当我从应用程序尝试它时,它不起作用。 Could someone please help me how to achieve my goal.有人可以帮助我如何实现我的目标。

code代码

 _pickImage = async () => {

        let result = await ImagePicker.launchImageLibraryAsync({
            mediaTypes: ImagePicker.MediaTypeOptions.All,
            quality: 1,
            allowsMultipleSelection: true,
            base64: true,
        });
        let pickerResult = await ImagePicker.launchImageLibraryAsync();

        if (!result.cancelled) {
            console.log('iff')
            ext = result.uri.split('.').pop()
            this.setState(prevState => ({
                images: [...prevState.images, `data:image/${ext};base64,` + result.base64],
                imageView: true
            })
            )

            axios.post(`${apiUrl}/api/cloud/image`,{image:pickerResult})
            .then(res=> {
                console.log('@@@@@@ response',res.data)
            })
            .catch(error=> {
                console.log('@@@@@@ error reponse',error.response.data)
            })

            // console.log('fffe', this.state.images)
            // this.props.dispatch(uploadImage(this.state.images))
        } else {
            console.log('else')
        }
    };

Update: Now the problem is that the size of sent file too large.更新:现在的问题是发送文件的大小太大。 Therefore, I suggest that you should choose not to selectMultiImage, and low down the quality first.所以建议大家不要选择MultiImage,先把画质调低。

So, I change the code a little bit:所以,我稍微修改一下代码:

_pickImage = async () => {

    let result = await ImagePicker.launchImageLibraryAsync({
        mediaTypes: ImagePicker.MediaTypeOptions.Images,
        quality: 0.1,
        allowsMultipleSelection: false,
        base64: true,
    });

    if (!result.cancelled) {
        let fd = new FormData()
        fd.append('imageKey',result.uri); /// file refer to result.uri
        axios({
            method: 'post',
            url: `${apiUrl}/api/cloud/image`,
            data: fd,
        })
        .then(res=> {
            console.log('@@@@@@ response',res.data)
        })
        .catch(error=> {
            console.log('@@@@@@ error reponse',error.response.data)
        })

        // console.log('fffe', this.state.images)
        // this.props.dispatch(uploadImage(this.state.images))
    } else {
        console.log('else')
    }
}

Solution reference : axios post request to send form data .解决方案参考: axios post请求发送表单数据

Try form-data:试试表格数据:

_pickImage = async () => {

    let result = await ImagePicker.launchImageLibraryAsync({
        mediaTypes: ImagePicker.MediaTypeOptions.All,
        quality: 1,
        allowsMultipleSelection: true,
        base64: true,
    });

    let pickerResult = await ImagePicker.launchImageLibraryAsync();

    /////////  assume that pickerResult return image file......

    if (!result.cancelled) {
        console.log('iff')
        ext = result.uri.split('.').pop()
        this.setState(prevState => ({
            images: [...prevState.images, `data:image/${ext};base64,` + result.base64],
            imageView: true
        })
        )
        let fd = new FormData()
        fd.append('imageKey',pickerResult);

        axios({
            method: 'post',
            url: `${apiUrl}/api/cloud/image`,
            data: fd,
        })
        .then(res=> {
            console.log('@@@@@@ response',res.data)
        })
        .catch(error=> {
            console.log('@@@@@@ error reponse',error.response.data)
        })

        // console.log('fffe', this.state.images)
        // this.props.dispatch(uploadImage(this.state.images))
    } else {
        console.log('else')
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM