使用 Widget 进行 Cloudinary 签名上传

mot*_*oto 1 javascript upload node.js cloudinary

文档非常令人沮丧。

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

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

我已经拼凑了我认为应该有效的内容,但它仍然说: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;
Run Code Online (Sandbox Code Playgroud)

也尝试过

return {
  signature,
  timestamp,
};
Run Code Online (Sandbox Code Playgroud)

也尝试过

const signature = cloudinaryV2.utils.api_sign_request(
      data.params_to_sign,
      CLOUDINARY_SECRET_KEY,
    );
Run Code Online (Sandbox Code Playgroud)

客户:

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);
  },
);
Run Code Online (Sandbox Code Playgroud)

Dem*_*tix 7

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

现在我已经把这个想法说出来了……我真的需要能够做到这一点,而且我花了太长时间把头撞到墙上,而这本来应该是非常简单的。这里是...

服务器(Node.js)

您需要一个向前端返回签名时间戳对的端点:

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 }
}
Run Code Online (Sandbox Code Playgroud)

客户端(浏览器)

客户端向服务器请求签名时间戳对,然后使用它来上传文件。示例中使用的文件应来自<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
}
Run Code Online (Sandbox Code Playgroud)

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