首页 > 解决方案 > React Native在android上发送数据[类型错误:网络请求失败]

问题描述

我正在尝试从 android 图片库中获取图片并将它们保存在我的 cloudinary 帐户中。我使用了 axios/fetch 并收到错误“网络请求失败”。下面是我的代码:

_pickImage = async () => {
    let result = await ImagePicker.launchImageLibraryAsync({
      allowsEditing: true,
      aspect: [4, 3],
    });

    let formData = new FormData();
    formData.append("file", result);
    formData.append("tags", 'text_detection');
    formData.append("upload_preset", "xxx");
    formData.append("api_key", "xxx");

    if (!result.cancelled) {
      this.setState({ image: result.uri });
    }

    return fetch("http://api.cloudinary.com/v1_1/ebrugulec/image/upload", {
      headers: {
        'Accept': 'application/json',
        'Content-Type': 'multipart/form-data'
      },
      method: 'POST',
      body: formData
    }).then(function(response){
      return response.json();
    }).catch(function(error) {
      console.log('There has been a problem with your fetch operation: ' + error.message)
    })
  }; 
}

标签: reactjsreact-nativefetchaxioscloudinary

解决方案


您正在尝试使用 Cloudinary REST API 上传,但没有签名。您应该签署上传请求并将签名添加为上传参数的一部分。

如何生成签名: https ://cloudinary.com/documentation/upload_images#generating_authentication_signatures

这是一个代码示例:https ://github.com/cloudinary/cloudinary_npm/issues/145#issuecomment-406852031

相反,您可以使用 Cloudniry SDK 来轻松上传图像。

——亚基尔


推荐阅读