带小部件的 Cloudinary 签名上传

Cloudinary Signed Uploads with Widget

文档非常令人沮丧。

我正在使用上传小部件来尝试允许用户为他们的个人资料上传多张照片。我不能使用未签名的上传,因为可能会被滥用。

我宁愿通过上传小部件而不是通过服务器上传文件,因为它看起来应该如此简单

我已经拼凑出我认为应该有效的内容,但它仍然在说:Upload preset must be whitelisted for unsigned uploads

服务器:

// grab a current UNIX timestamp
const millisecondsToSeconds = 1000;
const timestamp = Math.round(Date.now() / millisecondsToSeconds);
// generate the signature using the current timestmap and any other desired Cloudinary params
const signature = cloudinaryV2.utils.api_sign_request({ timestamp }, CLOUDINARY_SECRET_KEY);
// craft a signature payload to send to the client (timestamp and signature required)
return signature;

也试过

return {
  signature,
  timestamp,
};

也试过

const signature = cloudinaryV2.utils.api_sign_request(
      data.params_to_sign,
      CLOUDINARY_SECRET_KEY,
    );

客户:

const generateSignature = async (callback: Function, params_to_sign: object): Promise<void> => {
  try {
    const signature = await generateSignatureCF({ slug: 'xxxx' }); 
  // also tried { slug: 'xxxx', params_to_sign }
    callback(signature);
  } catch (err) {
    console.log(err);
  }
};
cloudinary.openUploadWidget(
  {
    cloudName: 'xxx',
    uploadPreset: 'xxxx',
    sources: ['local', 'url', 'facebook', 'dropbox', 'google_photos'],
    folder: 'xxxx',
    apiKey: ENV.CLOUDINARY_PUBLIC_KEY,
    uploadSignature: generateSignature,
  },
  function(error, result) {
    console.log(error);
  },
);

伙计。我讨厌我的生活。我终于弄明白了。从字面上看,我美化了上传小部件 js,才明白函数的 return 应该是字符串而不是对象,即使文档看起来不是这样。

以下是使用 Firebase 云函数实现签名上传的方法

import * as functions from 'firebase-functions';
import cloudinary from 'cloudinary';
const CLOUDINARY_SECRET_KEY = functions.config().cloudinary.key;
const cloudinaryV2 = cloudinary.v2;
module.exports.main = functions.https.onCall(async (data, context: CallableContext) => {
  // Checking that the user is authenticated.
  if (!context.auth) {
    // Throwing an HttpsError so that the client gets the error details.
    throw new functions.https.HttpsError(
      'failed-precondition',
      'The function must be called while authenticated.',
    );
  }
  try {
    return cloudinaryV2.utils.api_sign_request(data.params_to_sign, CLOUDINARY_SECRET_KEY);
  } catch (error) {
    throw new functions.https.HttpsError('failed-precondition', error.message);
  }
});


// CLIENT
const uploadWidget = () => {
  const generateSignature = async (callback: Function, params_to_sign: object): Promise<void> => {
    try {
      const signature = await generateImageUploadSignatureCF({ params_to_sign });
      callback(signature.data);
    } catch (err) {
      console.log(err);
    }
  };

  cloudinary.openUploadWidget(
    {
      cloudName: 'xxxxxx',
      uploadSignature: generateSignature,
      apiKey: ENV.CLOUDINARY_PUBLIC_KEY,
    },
    function(error, result) {
      console.log(error);
    },
  );
};

让我们花点时间指出 Cloudinary 的文档有多么糟糕。这很容易是我见过的最糟糕的。噩梦燃料。

现在我已经把它说出来了......我真的需要能够做到这一点,我花了太长时间用头撞墙,因为这本应该是非常简单的。这是...

服务器(Node.js)

您需要一个端点,该端点 returns 到前端的签名-时间戳对:

import cloudinary from 'cloudinary'

export async function createImageUpload() {
  const timestamp = new Date().getTime()
  const signature = await cloudinary.utils.api_sign_request(
    {
      timestamp,
    },
    process.env.CLOUDINARY_SECRET
  )
  return { timestamp, signature }
}

客户端(浏览器)

客户端向服务器请求签名-时间戳对,然后使用它来上传文件。示例中使用的文件应来自 <input type='file'/> 更改事件等

const CLOUD_NAME = process.env.CLOUDINARY_CLOUD_NAME
const API_KEY = process.env.CLOUDINARY_API_KEY

async function uploadImage(file) {
  const { signature, timestamp } = await api.post('/image-upload')
  const form = new FormData()
  form.append('file', file)
  const res = await fetch(
    `https://api.cloudinary.com/v1_1/${CLOUD_NAME}/image/upload?api_key=${API_KEY}&timestamp=${timestamp}&signature=${signature}`,
    {
      method: 'POST',
      body: form,
    }
  )
  const data = await res.json()
  return data.secure_url
}

就是这样。仅此而已。如果 Cloudinary 在他们的文档中有这个就好了。