3
votes
$http({method: 'POST', 
    url: $rootScope.CLOUDINARY_CONFIG.upload_url,
    data : {
      file : canvasImage,
      resource_type : 'image',
      format: "jpg",
      timestamp : 1375363550,
      api_key : $rootScope.CLOUDINARY_CONFIG.api_key,
      signature : signature,
      public_id : scope.model.public_id
    },
    headers : {"X-Requested-With": "XMLHttpRequest", "Content-Type" : "multipart/formData"}

    }).success(function(data, status, headers, config) {
          console.log("success");
    }).error(function(data, status, headers, config) {
          console.log("fail");
    });

I am trying to upload a base64 image to cloudinary account. I have already checked whether the signature, api key, upload url and canvasImage are correct. Yet whenever the request is sent,

I get an error in response :

 {"error":{"message":"Missing required parameter - file"}}

On checking the request payload i can see the file parameter being passed.

The canvasImage is the base64 jpg. of the sort - data:image/jpeg;base64,/9j/4AAQSkZJRgABA.

Can't find anything of this sort in the cloudinary documentation.

1

1 Answers

1
votes

Firstly, look into the FormData object. You'll want to use that if you're uploading multi-part form data.

Basically, the FormData object allows you to append files, blobs, and strings (if you attach something that isn't of those three, it will stringify it) using the only function that it has, append i.e:

var newForm = new FormData();

newForm.append('fileName', file);
newForm.append('api_key', $rootScope.CLOUDINARY_CONFIG.api_key);
newForm.append('signature', signature);
newForm.append(public_id, scope.model.public_id);

and so on..

Next.

Set your content-type to undefined instead of multi-part form data. This seems unintuitive, however, what happens is that the browser will automatically set the proper boundary for you and will automatically set the content-type back to multipart/formdata.

Additionally, add a transformRequest to the config set to angular.identity. The browser will try to serialize your form data, therefore you need to stop it from doing so by setting transformRequest to angular.identity.

The overall $http request should look something like this:

$http.post(url, newForm, {
  transformRequest: angular.identity,
  headers: {'Content-Type': undefined}
})
.success(function(data){
  // success
})
.error(function(err){
  // log error
})

Also note that FormData is tricky to deal with you because if you console your FormData object, i.e.(console.log(newForm)) all it will show is: FormData {append: function}