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

问题描述

我是React Native的新手,并尝试使用Axios上传图像,但得到:请求失败,状态码为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-尝试上传图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-21 23:50