直接 URL 调用上的云图像转换

时间:2021-07-12 05:29:54

标签: javascript node.js cloudinary

我正在尝试通过转换附带的直接 Cloudinary API 调用上传图像。现在,我只能上传没有像这样转换的图像:

...

    const fileList = files;
    const data = new FormData();
    const { signature, timestamp } = await getSignature(); // Get returned sign and timestamp
    data.append("file", fileList[0]);
    data.append("signature", signature); // Signature
    data.append("timestamp", timestamp); // Timestamp
    data.append("api_key", process.env.NEXT_PUBLIC_CLOUDINARY_KEY);
    const res = await fetch(
      `https://api.cloudinary.com/v1_1/${process.env.NEXT_PUBLIC_CLOUDINARY_NAME}/image/upload`,
      {
        method: "POST",
        body: data,
        mode: "cors",
      }
    );
    const file = await res.json();

...

但这一次,我尝试通过 URL 上传包含水印的图像。我尝试做类似的事情:

const res = await fetch(
      `https://api.cloudinary.com/v1_1/${process.env.NEXT_PUBLIC_CLOUDINARY_NAME}/image/upload/l_obra_watermark`,
      {
        method: "POST",
        body: data,
        mode: "cors",
      }
    );

但它总是出现 CORS 错误。是否可以通过 URL 应用转换?我还能怎么做?

2 个答案:

答案 0 :(得分:0)

您可以在上传预设中包含所需的转换,并在上传调用中使用此上传预设,如下所示:

data.append("upload_preset", my_preset);

您可以在此处阅读有关上传预设的信息:

https://cloudinary.com/documentation/upload_presets

答案 1 :(得分:0)

我意识到我没有正确使用语法。我通过阅读文档并将其应用于我自己的代码中了解到这一点,我意识到我应该像这样将转换放在签名中:

const cloudinaryHandler = async (
  _req: NextApiRequest,
  res: NextApiResponse
) => {
  // Must be UNIX format
  const timestamp = Math.round(new Date().getTime() / 1000);

  // Signature
  const signature = cloudinary.utils.api_sign_request(
    {
      timestamp: timestamp,
      eager: "w_400,h_400,g_south_east,x_5,y_5,l_obra_watermark,o_76",
    },
    process.env.CLOUDINARY_SECRET //API Secret (MUST BE HIDDEN IN ENV)
  );

  res.statusCode = 200;
  res.json({ signature, timestamp });
};

而不是在 data.append() 中。

这是我从中学到的文档:

https://cloudinary.com/documentation/upload_images#manual_signature_generation

相关问题