I am trying to upload an image using Cloudinary post API without using Cloudinary SDK

Viewed 965

I am new to cloudinary and Angular. I have been looking for a way to upload the image to cloudinary via without using SDK as cloudinary give us the option to upload the image using post API, I tried the following but didn't succeed.

uploadImage(event) {
var that = this;
this.create_blob(event.srcElement.files[0], function (blob_string) {
  that.http.post('https://api.cloudinary.com/v1_1/image/upload/', { file: blob_string}).subscribe(res => {
    // url of upload file
  })
});

}

 create_blob(file, callback) {
var reader = new FileReader();
reader.onload = function () { callback(reader.result) };
reader.readAsDataURL(file);}

I got the following error in console.

HttpErrorResponse {headers: HttpHeaders, status: 401, statusText: "Unauthorized", url: "https://api.cloudinary.com/v1_1/image/upload/", ok: false, …}
2 Answers

There are a few things that I can see based on the code you've provided:

  • You can inspect the response headers and look for one called X-Cld-Error which would provide more information regarding why the request failed. In this case, I would expect it to return cloud_name is disabled. This header is also present when requesting resources via Cloudinary delivery URLs which result in an error. E.g. https://res.cloudinary.com/demo/image/upload/ww_350/sample.jpg would return an X-Cld-Error header containing Invalid transformation parameter - ww.

  • Which relates to the next point, the upload API endpoint you're using doesn't include your cloud name. It should be https://api.cloudinary.com/v1_1/<cloud name>/image/upload

  • Client-side uploads (i.e. ones that are performed without an authentication signature) require an unsigned upload preset to be set up within your account and supplied alongside the file as the two mandatory parameters. Upload presets provide a way to define the upload parameters that would normally be allowed to be set directly in the upload call when using a signature. When not using a signature a lot of those parameters cannot be specified, and if required, should be configured within the upload preset. You can find out more on this, including how the upload preset can be created in this section of the documentation: https://cloudinary.com/documentation/upload_images#unsigned_upload

You are making a minor mistake that you missed to add cloud_name in your post request. You can find your cloud_name by visiting the Cloudinary dashboard. The correct code is as follows

    uploadImage(event) {
    var that = this;
    this.create_blob(event.srcElement.files[0], function (blob_string) {
    that.http.post('https://api.cloudinary.com/v1_1/YOUR_CLOUD_NAME/image/upload/', { file:  blob_string}).subscribe(res => {
    // url of upload file
  })

Note: The following method is uploading the using unsigned way so when you try to download image its url will be started as "http" not "https"

Related