user7747472
user7747472

Reputation: 1952

How can i upload image to server using axios in react native?

I want to upload an image file to the server in react native, how can i do so? Here is my code :

In my index.js Which is my entry point I have set axios default configurations :

axios.defaults.baseURL = BaseUrl;
axios.defaults.headers.common['Content-Type'] = 'application/json';
axios.defaults.headers.common['Accept'] = 'application/json';

Now in my profileEdit.js, where I need to upload a profile image

  let data = new FormData();
  data.append('profile_picture',
      {uri: imageResponse.uri, name: imageResponse.fileName, type: 'image/jpg'});

// imageResponse is a response object that I m getting from React native  ImagePicker 

    axios.post('profile/picture/', data,
       {
          headers: {
                    "Authorization": "JWT " + this.state.token,
                    'content-type': 'multipart/form-data',
                  }
        }).then(response => {
                console.log('Profile picture uploaded successfully', response);

        }).catch(error => {
              console.log('Failed to upload profile image', error);
              console.log('Error response',error.response);

        });

But this giving me network error, while other APIs are working fine.

I followed the solution given here How to upload image to server using axios in react native?

This is the error response I am getting

This is the error response I am getting.

And my request header is like this enter image description here

I don't want to use any other package such as react native fetch blob

More links that I followed :

Can anyone please tell me where I m doing wrong or how shall I approach to this problem. ty

Upvotes: 1

Views: 4158

Answers (2)

Khurshid Ansari
Khurshid Ansari

Reputation: 5095

For me simply work

const oFormData = new FormData();
oFormData.append("image", {
uri: images.uri,
type: images.type,
name: images.fileName
});

axios.post(servicesUrl.imageupload, oFormData);

Upvotes: 0

Benji
Benji

Reputation: 380

I think your header for the Axios POST request may be incorrect since you're using a FormData() constructor to store your image data:

You may want to try the following instead:

let data = new FormData();
data.append('profile_picture',{
  uri: imageResponse.uri,
  name: imageResponse.fileName,
  type: 'image/jpg'}
);

axios.post('profile/picture/', data,
  {
    headers: {
      'content-type': `multipart/form-data; boundary=${data._boundary}`,
      ...data.getHeaders()
    }
  }
)

Upvotes: 3

Related Questions