javascript 如何使用fetch将图像上传到Cloudinary

qoefvg9y  于 2022-12-17  发布在  Java
关注(0)|答案(1)|浏览(182)

我尝试从我的前端使用fetch上传一个文件到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设置有'unsigned'上传预设在这里:

chhqkbe1

chhqkbe11#

如果我用const data = new FormData()...替换body: JSON.stringify(...),它就可以工作。我不知道为什么,但它可以工作:

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!
  });
}

相关问题