简体   繁体   中英

Cloudinary Base64 Image uploading in angularjs

$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.

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 ie:

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, ie(console.log(newForm)) all it will show is: FormData {append: function}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM