React Native - Axios - Trying to upload image

15,248

Solution 1

Can't be sure but in my case I had to add a 'name' field to the file. Following other advices, I've end up with something like this:

import axios from 'axios';
import FormData from 'form-data';

function upload (data, images, token) {
  const formData = new FormData();
  formData.append('data', data);
  images.forEach((image, i) => {
    formData.append('images', {
      ...image,
      uri: Platform.OS === 'android' ? image.uri : image.uri.replace('file://', ''),
      name: `image-${i}`,
      type: 'image/jpeg', // it may be necessary in Android. 
    });
  });
  const client = axios.create({
    baseURL: 'http://localhost:3001',
  });
  const headers = {
    Authorization: `Bearer ${token}`,
    'Content-Type': 'multipart/form-data'
  }
  client.post('/items/save', formData, headers);
}

Solution 2

I found the solution. First I needed to remove file:// from my uri so i added the code :

const fileURL = this.state.pickedImaged.uri;
const cleanURL = fileURL.replace("file://", "");

and than what caused the problem was the image type, please check what image type you try to upload and what you can upload depending on the backend you are using.

Hope will help someone who has the same problem

Solution 3

I had the same issue and this is what helped me.

  1. In android/app/src/main/java/com/{yourProject}/MainApplication.java comment the below line :

    initializeFlipper(this, getReactNativeHost().getReactInstanceManager())
    
  2. In android/app/src/debug/java/com/{yourProject}/ReactNativeFlipper.java comment in line 43 :

    builder.addNetworkInterceptor(new FlipperOkhttpInterceptor(networkFlipperPlugin));
    
  3. Code for image upload :

    var formData = new FormData();
       formData.append('UserId', '[email protected]');
       formData.append('VisitId', '28596');
       formData.append('EvidenceCapturedDate', '09/10/2019 13:28:20');
       formData.append('EvidenceCategory', 'Before');
       formData.append('EvidenceImage', {
         uri: Platform.OS === 'android' ? `file:///${path}` : path,
         type: 'image/jpeg',
         name: 'image.jpg',
       });
       axios({
         url: UrlString.BaseUrl + UrlString.imageUpload,
         method: 'POST',
         data: formData,
         headers: {
           Accept: 'application/json',
           'Content-Type': 'multipart/form-data'
         },
       })
         .then(function (response) {
           console.log('*****handle success******');
           console.log(response.data);
    
         })
         .catch(function (response) {
           console.log('*****handle failure******');
           console.log(response);
         });
    
Share:
15,248
laja
Author by

laja

Updated on June 09, 2022

Comments

  • laja
    laja almost 2 years

    I am new to React Native and trying to upload Image with Axios but getting: Request failed with status code 500

    I don't have backend problem because I can upload image with postman and everything is fine.

    Here is my code, please help me if you know a solution, when I console log data, all the data are fine!!

    const data = new FormData();
            data.append('name', name);
            data.append('childrenImage', childrenImage);
            data.append('parent', parent)
    
            console.log(data);
    
            axios.post('http://192.168.0.24:3000/childrens/', data, {
                    headers: {
                        'Authorization': auth,
                        'accept': 'application/json',
                        'Content-Type': `multipart/form-data`
                    }
                }
            ).then(res => {
                console.log(res.data);
                console.log(res.status);
            })
            .catch(err => {
                console.log(err.message);
            });

  • laja
    laja over 5 years
    Thanks for your response but this is what I am doing also, it just doesn't work with react native !!
  • Luong Truong
    Luong Truong over 4 years
    Can you please edit it to your full code? I don't know where to put the uri. Thank you in advance!
  • bhaRATh
    bhaRATh almost 4 years
    Try "Content-Type": "application/x-www-form-urlencoded", Accept: "application/json"
  • Sushmit Sagar
    Sushmit Sagar over 3 years
    Thanks MIME type is what i was missing.
  • Khurshid Ansari
    Khurshid Ansari almost 3 years
    i saw some post they remove file:///
  • Rahman Haroon
    Rahman Haroon over 2 years
    I have the same issue..I can upload from post man but cant upload from real device both ios and android.. i tried this and not work for me
  • Cid
    Cid almost 2 years
    Make sure to set both name and type as the properties of the object which is passed as the 2nd argument to formData.append (as is done in the answer, It is easy to overlook that), for me, not setting them, caused weird problems on server by which I mean server did not recognized the file upload operation.
  • techie18
    techie18 almost 2 years
    @ABM can help me out. file upload to server using form data with axios is not working