【问题标题】:How to upload image to server using axios in react native?如何使用 axios 在 react native 中将图像上传到服务器?
【发布时间】:2019-03-20 16:23:19
【问题描述】:

我想将图像作为文件发送到本机反应的服务器。我怎样才能做到这一点? 这是我的代码:-

export const editUserProfile = (sessionId,firstName,lastName,image,countryCode,phone) => 
new Promise((resolve,reject) => {

    const form = new FormData();
    form.append('image',{
        uri : image,
        type : 'image/jpeg',
        name : 'image.jpg'
    })
        return axios.post(base_url+'edit-profile',{
            session_id : sessionId, 
            firstname : firstName,  
            lastname : lastName,
            image : null,  
            country_code : countryCode, 
            phone : phone, 
            locale : 'en'
        }).then(response =>     
            {resolve(response)})
        .catch(error => 
            {reject(error)});
    });

【问题讨论】:

标签: javascript node.js react-native ecmascript-6


【解决方案1】:
//edit user profile
export const editUserProfile = 
    (sessionId,firstName,lastName,image,countryCode,phone) => 
new Promise((resolve,reject) => {

    var data = new FormData();
    data.append('session_id',sessionId);
    data.append('firstname',firstName);
    data.append('lastname',lastName);
    data.append('image',
      {
         uri:image,
         name:'userProfile.jpg',
         type:'image/jpg'
      });
    data.append('country_code',countryCode);
    data.append('phone',phone);
    data.append('locale','en');

        return axios.post(base_url+'edit-profile',data).then(response =>     
            {resolve(response)})
        .catch(error => 
            {reject(error)});
    });

【讨论】:

  • 我收到错误Request failed with status code 422。有什么问题?
  • 对不起,不是代码端的错误,找了很久才发现,是服务器端的错误。
  • 如果我们使用图像选择器返回一个对象,该对象具有 uri 等图像详细信息,输入但没有名称。
  • 我们不需要任何特殊的标题来发送图像或其他文件
  • name 是图像的名称来识别图像,就像它的用户图像一样,所以我设置名称 userProfile.jpg....或者你也可以使用从图像选择器中选择的 imageObject 的名称....
【解决方案2】:

在浪费了一整天之后,我才找到了解决方案。 首先找到您的图像的文件路径。我的是这个。

file:///storage/emulated/0/Pictures/f5ca988c-882d-4b5e-86bb-b47939909b09.jpg

从这里改为

file://storage/emulated/0/Pictures/f5ca988c-882d-4b5e-86bb-b47939909b09.jpg 有效 :)。只需删除第三个反斜杠即可。

【讨论】:

  • 它对我不起作用并且在发布“没有这样的文件或目录”时出错
【解决方案3】:

我也被这个问题困了一个星期。经过研究,我发现我们正在从 RN 向服务器发送超过 10MB 的文件,这些文件无法到达服务器。您可以调整图像大小并发送到服务器。这个包对我有帮助。 https://github.com/bamlab/react-native-image-resizer

【讨论】:

    猜你喜欢
    • 2019-10-27
    • 2019-05-01
    • 1970-01-01
    • 2020-02-15
    • 2021-12-31
    • 2021-05-29
    • 2018-08-24
    • 2016-12-06
    • 1970-01-01
    相关资源
    最近更新 更多