Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React Native - Axios - Trying to upload image

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);
        });
like image 998
laja Avatar asked Oct 22 '18 20:10

laja


1 Answers

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);
}
like image 103
Pedro Andrade Avatar answered Sep 20 '22 02:09

Pedro Andrade