reactjs 在React中使用Axios将多个文件上传到Cloudinary

e5nqia27  于 2023-05-22  发布在  React
关注(0)|答案(1)|浏览(182)

我尝试过在axios中实现超级代理上传多个文件的方式。但不知怎么的,我在控制台得到一个错误
无法加载https://api.cloudinary.com/v1_1/xxxx/image/upload:预检响应中的Access-Control-Allow-Headers不允许请求标头字段Authorization。
我的上传处理程序如下所示

uploadFile(){
      const uploaders = this.state.filesToBeSent.map(file => {
             const formData = new FormData();
             formData.append("file", file);
             formData.append("upload_preset", "xxxxx"); 
             formData.append("api_key", "xxxxx");
             formData.append("timestamp", (Date.now() / 1000) | 0);

             return axios.post(url, formData, {
               headers: { "X-Requested-With": "XMLHttpRequest" },
             }).then(response => {
               const data = response.data;
               const fileURL = data.secure_url 
               console.log(data);
             })
         });

    // Once all the files are uploaded
    axios.all(uploaders).then(() => {
      // ... perform after upload is successful operation
      console.log("upload completed ", uploaders);
    });
  }

这个例子来自here
还有一件事让我很困惑。在superagent中,我们可以将参数附加到请求字段,其中包括Cloudinary的API密钥,如下所示:

const paramsStr = 'timestamp='+timestamp+'&upload_preset='+uploadPreset+secretKey;
     const signature = sha1(paramsStr);

      const params = {
        'api_key': 'xxxx',
        'timestamp': timestamp,
       'upload_preset': uploadPreset,
        'signature': signature
     }

      Object.keys(params).forEach(key => {
        uploadRequest.field(key, params[key])
      });

但是在该示例中,没有提到如何将密钥和其他参数附加到axios。

pieyvz9o

pieyvz9o1#

您需要在后端生成签名,然后使用生成的签名执行上传。您可以通过以下指令生成签名-https://support.cloudinary.com/hc/en-us/articles/203817991-How-to-generate-a-Cloudinary-signature-on-my-own-
您还可以查看以下示例,了解如何将签名附加到请求中。它是在PHP中,但是,准则仍然适用。https://gist.github.com/taragano/a000965b1514befbaa03a24e32efdfe5

相关问题