React Native - Axios - 尝试上传图片 [英] React Native - Axios - Trying to upload image

查看:98
本文介绍了React Native - Axios - 尝试上传图片的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是 React Native 的新手,并尝试使用 Axios 上传图像但得到:Request failed with status code 500

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

推荐答案

不能确定,但​​在我的情况下,我不得不向文件中添加一个名称"字段.按照其他建议,我最终得到了这样的结果:

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

这篇关于React Native - Axios - 尝试上传图片的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆