Direct Upload to Cloudinary from Browser Bad Reque

2019-08-10 13:31发布

问题:

i'm getting a 400 bad request error when trying to upload to cloudinary with the following code:

$("input.cloudinary-fileupload[type=file]").cloudinary_fileupload();
$.cloudinary.config({"api_key":"6586856745648955","cloud_name":"some-cloud"});

  $http.get("http://localhost:3000/story/secret")
  .then(function(res){
    var CLOUD_API_SECRET = res.data.CLOUD_API_SECRET;
    var obj =
    {
      "timestamp":  Date.now(),
      "callback": "http://localhost:3000/cloudinary_cors",
      "signature": CLOUD_API_SECRET,
      "api_key": "6586856745648955"
    };
    // var data = JSON.stringify(obj);
    $("input[type='file']").attr('data-form-data', obj);
  })
  .catch(function(err){
    console.log("error: ", err);
  });

with my front containing the following:

<input name="file" type="file"
    class="cloudinary-fileupload" data-cloudinary-field="image_upload"
    data-form-data=" ... html-escaped JSON data ... " >
</input>

i've also tried to stringify, then encode the "obj" variable and plug that in like so:

var data = JSON.stringify(obj);
$("input[type='file']").attr('data-form-data', encodeURI(data));

i get the same error.

i'd appreciate any help or suggestions. thanks a bunch.

回答1:

There are a few issues here:

  1. Your account's api_secret should never be revealed in your client-side code.
  2. The signature isn't the api_secret, you should generate a signature which is based on both your api_secret and the upload options. For more information: http://cloudinary.com/documentation/upload_images#request_authentication. The signature generation must be done on a server-side.
  3. Cloudinary expects the signature to be based on the timestamp by seconds and not milliseconds, so the last 3 digits are not necessary. Therefore, I'd recommend you to divide the timestamp by 1000 to omit the last 3 digits (e.g., Date.now()/1000)