Search code examples
androiddjangoreact-nativeaxiosuri

Not able to upload images to Django Server using React Native app


I have a react native android app and a Django REST API. Using react-native-image-picker the user is able to select an image and the image successfully shows up in the react native app.

But then, I want to upload it to the API. For this, I am sending an axios request. When I send the request with image as null the request has a successful response. But, when the user selects an image then this request gives the following error: [Error: Request failed with status code 400]

In the Django API, this image is defined as: image = models.ImageField(upload_to='media/Images/Groups/', null=True)

I know this is not the issue, because when I upload an image from the Django Administration, it successfully uploads the image as required.

And here is the API request to upload this image (and I know this is also not causing the issue):

const axios = require("axios");
   await axios.post('http://the url..., {
       //other fields I'm adding here
       "image": this.state.gImage,
   })
   .then((response) => {
       console.log(response);
   }, (error) => {
       console.log(error);
});

What I think the issue is, its in uri of the image that the user selects. When the user selects the image from the phone's gallery, then the image uri (which is in this.state.gImage) as displayed on the console is:

{"uri": "content://com.google.android.apps.photos.contentprovider/0/1/content%3A%2F%2Fmedia%2Fexternal%2Fimages%2Fmedia%2F35531/ORIGINAL/NONE/image%2Fpng/613917948"}

Does anyone have a solution? Or what could actually be causing the error?


Solution

  • I should be something like this:

    const form = new FormData();
    form.append('other-field', 'xyz');
    form.append('image', {
            uri: pickerResponse.uri,
            name: pickerResponse.name,
            type: pickerResponse.type
        });
    
    axios.post('url', form)
            .then(res => {
                //response
            }).catch(err=>{
                //error
            })