Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
244 views
in Technique[技术] by (71.8m points)

javascript - 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);
        });
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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);
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...