在Cloudinary上使用axios上传React-Native imagePicker

时间:2020-04-12 15:53:16

标签: react-native axios cloudinary

我尝试从本地主机和产品环境的相机库上传一些图像。我的代码使用有效的网址,例如:https://res.cloudinary.com/dtdiwoz7o/image/upload/v1586706052/cn-2016-sashaonyshchenko-1920x1920-1510074905_dyfldk.jpg 但是,当我通过图像文件路径时,将返回400错误。 这是我的代码,带有一些日志:

  _avatarClicked = () => {
const options = {
  title: 'Select Photo',
  storageOptions: {
    skipBackup: true,
    path: 'images',
  },
};
ImagePicker.showImagePicker(options, (response) => {
  if (response.didCancel) {
    return
  }
  else if (response.error) {
    return
  }
  else {

    let data = {
      file: response.uri,
      upload_preset: "my_preset_name",
    }

    axios.post("https://api.cloudinary.com/v1_1/my_cloud_name/image/upload", data)
      .then(res => console.log(res))
      .catch(err => console.log(err))

  }
})

}

我的repsponse.uri的

日志: (文件:/// Users / clement / Library / Developer / CoreSimulator / Devices / 62E85527-A2AC-46CD-B517-E6039F99E056 / data / Containers / Data / Application / E218E950-3A1C-40EB-8289-3837EC89FBBB / Documents / images / 46674162-E32B-4302-B28A-5EF9150206D0.jpg)

我试图用此'const source'在数据文件中替换它,但是它不起作用:

     const source = {
      uri: response.uri,
      type: response.type,
      name: response.fileName,
    }

我在react-native)图像选择器文档上看到并测试了这个,但是我遇到了同样的400错误...

 // const source = { uri: 'data:image/jpeg;base64,' + response.data };

我也尝试使用Base64.encode(response.url)或Base64.encodeURI(response.url)

请,你能帮我吗? 对不起,我的英语不好

“ react-native”:“〜0.61.4”, “ react-native-image-picker”:“ ^ 2.3.1”,

//////////////////////////

我找到了解决方法:

  let data = {
  file: 'data:image/jpg;base64,' + response.data,
  upload_preset: "my_preset_name",
}

axios.post("https://api.cloudinary.com/v1_1/my_cloud_name/image/upload/", data)
  .then(res => console.log(res))
  .catch(err => console.log(err))

1 个答案:

答案 0 :(得分:2)

好的,我找到了解决方法:

  let data = {
      file: 'data:image/jpg;base64,' + response.data,
      upload_preset: "my_preset_name",
    }

    axios.post("https://api.cloudinary.com/v1_1/my_cloud_name/image/upload/", data)
      .then(res => console.log(res))
      .catch(err => console.log(err))