7

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
  • 143
  • 1
  • 2
  • 8

6 Answers6

13

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,556
  • 1
  • 25
  • 24
  • Thanks MIME type is what i was missing. – Sushmit Sagar Sep 04 '20 at 16:30
  • 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. – Gandalf Jun 27 '22 at 17:31
  • Very helpful example, though I'm not clear, what keys/values is `...image` spreading into the object? – blwinters Jan 18 '23 at 14:28
7

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
  • 565
  • 7
  • 18
  • 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
  • @ABM can help me out. file upload to server using form data with axios is not working –  Jul 06 '22 at 13:57
4

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
  • 143
  • 1
  • 2
  • 8
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,473
  • 35
  • 181
  • 253
murugan mani
  • 375
  • 5
  • 6
0

Two things are important on Android; Setting the 'Content-Type': 'multipart/form-data'

Also, make sure the type on your Blob is a valid MimeType. In my case, I was passing type: 'image', in iOS, it worked fine, but on android, it didn't work until I updated it to type: 'image/jpeg' accordingly.

Joseph Ajibodu
  • 1,093
  • 10
  • 14
-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