【问题标题】:How to upload an image to Cloudinary with fetch如何使用 fetch 将图片上传到 Cloudinary
【发布时间】:2022-12-16 20:22:03
【问题描述】:

我正在尝试使用从我的前端获取的文件将文件上传到 Cloudinary。我尝试从文档和 StackOverflow 答案中拼凑出执行此操作的方法,但出现 400 错误:

export async function uploadImageToCloudinary(file: File) {
  const url = `https://api.cloudinary.com/v1_1/${cloudName}/upload`;
  const fetched = await fetch(url, {
    method: "post",
    body: JSON.stringify({
      file,
      cloud_name: cloudName,
      upload_preset: "unsigned",
    }),
  });
  const parsed = await fetched.json()
  console.log({
    parsed // 400 error, message: "Upload preset must be specified when using unsigned upload"
  });
}

它说必须指定上传预设,所以我上面的代码一定是错误的。我的 Cloudinary 设置在此处具有“未签名”上传预设:

【问题讨论】:

    标签: javascript typescript fetch-api cloudinary


    【解决方案1】:

    如果我将 body: JSON.stringify(...) 替换为 const data = new FormData()...,它就会工作。我不知道为什么,但这有效:

    export async function uploadImageToCloudinary(file: File) {
      const url = `https://api.cloudinary.com/v1_1/${cloudName}/upload`;
      const data = new FormData();
      data.append('file', file);
      data.append('upload_preset', 'unsigned');
    
      const fetched = await fetch(url, {
        method: "post",
        body: data,
      });
      const parsed = await fetched.json()
      console.log({
        parsed // 200, success!
      });
    }
    

    【讨论】:

      猜你喜欢
      • 2020-09-20
      • 2021-09-29
      • 2019-02-14
      • 2019-05-07
      • 2021-04-22
      • 2022-01-12
      • 2018-03-15
      • 2016-09-20
      • 2018-06-04
      相关资源
      最近更新 更多