6

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
  • 103
  • 1
  • 1
  • 8

5 Answers5

12

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);
}
Pedro Andrade
  • 4,357
  • 1
  • 20
  • 21
3

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

laja
  • 103
  • 1
  • 1
  • 8
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', 'abc@abc.com');
       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);
         });
    
ABM
  • 445
  • 5
  • 15
  • 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 – Rahman Haroon Sep 17 '21 at 08:51
0

FLIPPER_VERSION=0.33.1 to FLIPPER_VERSION=0.41.0

Need to update your Flipper_Version above or equal = 0.41.0 after update it's working fine.

Eric Aya
  • 69,000
  • 34
  • 174
  • 243
murugan mani
  • 345
  • 3
  • 6
-2

in react I use the following code:

//Set file in state
fileChangedHandler = (event) => {
    this.setState({ selectedFile: event.target.files[0] })
  }

//Set form data and request in axios
uploadHandler = () => {
    const formData = new FormData();
    console.log(this.state.selectedFile)
    formData.append('file', this.state.selectedFile, this.state.selectedFile.name);

    axios.post('http://localhost:3000/api/uploadFile', formData)
      .then((response) => {
        console.log(response)
        }
      .catch((err) => {
        console.log(err)
      })

In the back-end receive the file and test with console.log(req.files)

I hope to have helped you :)

Herbert
  • 1
  • 1