上传到cloudary API -无效的文件参数

Uploading to Cloudinary API - Invalid file parameter

本文关键字:无效 文件 参数 API cloudary      更新时间:2023-09-26

我正在努力将cloudary与我的React Native应用程序集成,当我使用cloudary API进行上传时,我遇到了一个问题。我使用React Native Image Picker从相机胶卷中选择一个图像,并使用它获得一个源uri -示例如下。

我从cloudary得到一个错误响应,我不确定它指的是什么。"Invalid file parameter. Make sure your file parameter does not include '[]'"

当我使用调试器时,我可以控制台注销我在请求体中发送的所有参数。任何建议将非常感激!

source.uri: /Users/IRL/Library/Developer/CoreSimulator/Devices/817C678B-7028-4C1C-95FF-E6445FDB2474/data/Containers/Data/Application/BF57AD7E-CA2A-460F-8BBD-2DA6846F5136/Documents/A2F21A21-D08C-4D60-B005-67E65A966E62.jpg

async postToCloudinary(source) {
let timestamp = (Date.now() / 1000 | 0).toString();
let api_key = ENV.cloudinary.api;
let api_secret = ENV.cloudinary.api_secret
let cloud = ENV.cloudinary.cloud_name;
let hash_string = 'timestamp=' + timestamp + api_secret
let signature = CryptoJS.SHA1(hash_string).toString();
let upload_url = 'https://api.cloudinary.com/v1_1/' + cloud + '/image/upload'
try {
  let response = await fetch(upload_url, {
    method: 'POST',
    headers: {
      'Accept': 'application/json',
      'Content-Type': 'application/json'
    },
    body: JSON.stringify({
      file: {
        uri: source.uri,
        type: 'image/jpeg'
      },
      api_key: api_key,
      timestamp: timestamp,
      signature: signature
    })
  });
  let res = await response.json();
  console.log(res);
} catch(error) {
  console.log("Error: ", error);
}

}

所以我现在有base64编码工作,我认为,但我仍然得到相同的错误。

var wordArray = CryptoJS.enc.Utf8.parse(source.uri);
var file = CryptoJS.enc.Base64.stringify(wordArray);
try {
  let response = await fetch(upload_url, {
    method: 'POST',
    headers: {
      'Accept': 'application/json',
      'Content-Type': 'application/json'
    },
    body: JSON.stringify({
      file: {
        uri: file,
        type: 'image/jpeg;base64'
      },
      api_key: api_key,
      timestamp: timestamp,
      signature: signature
    })
  });

所以我传入的源数据格式不正确。我能够从ImagePicker插件中传递它,我使用它作为一个已经格式化的数据URI (ImagePicker示例有两种方法来捕获源文件,我使用了错误的一个)。我能够摆脱CryptoJS的东西,简单地通过file: source.uri

如果您正在使用axios,请确保在请求头中包含{'X-Requested-With': 'XMLHttpRequest'}。如:

const uploadAgent = axios.create({
  baseURL: 'https://api.cloudinary.com',
  headers: {
    'X-Requested-With': 'XMLHttpRequest'
  }
});