Cloudinary服务端图片上传签名失败

Cloudinary server-side image upload signature fails

我正在开发一个上传用户徽标或图像的程序。 为此,我首先在服务器端创建一个签名,然后使用该签名将图像从客户端上传到 cloudinary。

问题是我总是收到以下错误: `无效的签名“b4000077c554448649396c31750e27141820693c”。要签名的字符串 - 'source=uw&timestamp=1598531294&upload_preset=signed-preset'.`` (具有不同的签名和时间戳 ofc。)

我遵循了他们文档中的指南:https://cloudinary.com/documentation/upload_images#generating_authentication_signatures 但是没有帮助,

这是客户端代码:

 let signature = '';
    let timestamp = '';

    let generateSignature = function (callback, params_to_sign) {
        $.ajax({
            url: "/business/create-cloudinary-signature",
            type: "GET",
            dataType: "text",
            data: { data: params_to_sign },
            complete: function () { console.log("complete") },
            success: function (response, textStatus, xhr) {
                const res = JSON.parse(response);
                console.log(res.signature)
                signature = res.signature;
                timestamp = res.timestamp;
                console.log(signature, timestamp);
                callback(signature);
            },
            error: function (xhr, status, error) { console.log(xhr, status, error); }
        });
    }

    console.log(signature, timestamp) //correct values

    const uploadSettings = {
        apiKey: "816773373496447",
        cropping: true,
        cloudName: 'rav-chesed',
        uploadPreset: 'signed-preset'

    }

    var myWidget = cloudinary.createUploadWidget({ ...uploadSettings, uploadSignature: generateSignature, uploadSignatureTimestamp: timestamp }, (error, result) => {
        if (error) {
            console.log(error)
        }
        if (!error && result && result.event === "success") {
            console.log('Done! Here is the image info: ', result.info);
        }
    }
    )
    document.getElementById("logoUploader").addEventListener("click", function () {
        myWidget.open();
    }, false);   
    

这是服务器端代码 (nodejs)

router.get("/create-cloudinary-signature", (req, res) => {
  console.log("heyy");
  console.log(req.query);
  const data = req.query.data;

  // // Get the timestamp in seconds
  // var timestamp = Math.round(new Date().getTime() / 1000);
  // console.log(timestamp);
  data.timestamp = Number(data.timestamp);
  // console.log(data);

  // // Show the timestamp
  // console.log("Timestamp:", timestamp);
  // const sts = `source=${data.source}&timestamp=${data.timestamp}&upload_preset=${data.upload_preset}`;
  // console.log(sts);

  // function sortObjKeysAlphabetically(obj) {
  //   var ordered = {};
  //   Object.keys(obj)
  //     .sort()
  //     .forEach(function (key) {
  //       ordered[key] = obj[key];
  //     });
  //   return ordered;
  // }

  // var sortedObj = sortObjKeysAlphabetically(data);
  // console.log(sortedObj);
  // params_to_sign via string
  var params_to_sign =
    "source=" +
    data.source +
    "&timestamp=" +
    data.timestamp +
    "&upload_preset=" +
    data.upload_preset;
  console.log(params_to_sign);

  // Get the signature using the Node.js SDK method api_sign_request
  var signature = cloudinary.utils.api_sign_request(
    params_to_sign,
    process.env.CLOUDINARY_API_SECRET
  );
  console.log(signature);
  res.json({ signature, timestamp: data.timestamp });
});

我得到了正确的数据,我什至得到了一个哈希返回给客户端,但由于某种原因,签名无效,我无法上传图像。

在此方面提供一些帮助,我们将不胜感激。 提前致谢。

api_sign_request 函数采用散列(对象)和 API 秘密字符串。在这种情况下,您将提供一个字符串 (params_to_sign) 作为第一个参数。

你可以做的是直接将 data 作为第一个参数传递给 api_sign_request 而不做任何修改。这将包含所有需要的参数,并与 front-end 上传小部件发送的内容完全匹配。

在他们的支持下几个小时后,我想我自己弄明白了,

看起来生成签名的代码与我使用的版本不兼容。 在他们的文档中,他们要求使用 var cloudinary = require("cloudinary").v2; 但是在我将它改回 var cloudinary = require("cloudinary"); 之后,一切都开始正常工作了。

我还做了一些代码修改: 服务器端:

router.get("/create-cloudinary-signature", (req, res) => {
  console.log("heyy");
  //console.log(req.query);
  const data = req.query.data;
  console.log(data);
  const timeStampSignature = Math.round(new Date() / 1000);
  console.log(timeStampSignature);


  // Get the signature using the Node.js SDK method api_sign_request
  var signature = cloudinary.utils.api_sign_request(
    data,
    process.env.CLOUDINARY_API_SECRET
  );
  console.log(signature);
  res.json({ signature: signature, timestampSignature: timeStampSignature });
});

和client-side:

<script type="text/javascript">
    let signature = '';
    let timestampSignature = '';

    let generateSignature = function (callback, params_to_sign) {
        $.ajax({
            url: "/business/create-cloudinary-signature",
            type: "GET",
            dataType: "text",
            //params _to_sign contains timestamp
            data: { data: params_to_sign },
            complete: function () { console.log("complete") },
            success: function (response, textStatus, xhr) {
                const res = JSON.parse(response);
                //console.log(res.signature)
                signature = res.signature;
                timestampSignature = res.timestampSignature;
                console.log(signature, timestampSignature);

                callback(signature);
            },
            error: function (xhr, status, error) { console.log(xhr, status, error); }
        });
    }

    const uploadSettings = {
        apiKey: "blabla",
        cropping: true,
        cloudName: 'name',
        uploadPreset: 'signed-preset'
    }

    var myWidget = cloudinary.createUploadWidget({ ...uploadSettings, uploadSignature: generateSignature, uploadSignatureTimestamp: timestampSignature }, (error, result) => {
        if (error) {
            console.log(error)
        }
        if (!error && result && result.event === "success") {
            console.log('Done! Here is the image info: ', result.info);
        }
    }
    )
    document.getElementById("logoUploader").addEventListener("click", function () {
        myWidget.open();
    }, false);
</script>