Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cloud Code: Creating a Parse.File from URL

I'm working on a Cloud Code function that uses facebook graph API to retrieve users profile picture. So I have access to the proper picture URL but I'm not being able to acreate a Parse.File from this URL.

This is pretty much what I'm trying:

    Parse.Cloud.httpRequest({
        url: httpResponse.data["attending"]["data"][key]["picture"]["data"]["url"],
        success: function(httpImgFile) 
        {
            var imgFile = new Parse.File("file", httpImgFile);                                             
            fbPerson.set("profilePicture", imgFile); 
        },
        error: function(httpResponse) 
        {
            console.log("unsuccessful http request");
        }
    });

And its returning the following:

Result: TypeError: Cannot create a Parse.File with that data.
    at new e (Parse.js:13:25175)
    at Object.Parse.Cloud.httpRequest.success (main.js:57:26)
    at Object.<anonymous> (<anonymous>:842:19)

Ideas?

like image 713
adolfosrs Avatar asked Mar 15 '23 04:03

adolfosrs


1 Answers

I was having trouble with this exact same problem right now. For some reason this question is already top on Google results for parsefile from httprequest buffer!

The Parse.File documentation says

The data for the file, as 1. an Array of byte value Numbers, or 2. an Object like { base64: "..." } with a base64-encoded String. 3. a File object selected with a file upload control. (3) only works in Firefox 3.6+, Safari 6.0.2+, Chrome 7+, and IE 10+.

I believe for CloudCode the easiest solution is 2. The thing that was tripping me earlier is that I didn't notice it expects an Object with the format { base64: {{your base64 encoded data here}} }.

Also Parse.Files can only be set to a Parse.Object after being saved (this behaviour is also present on all client SDKs). I strongly recommend using the Promise version of the API as it makes much easier to compose such asynchronous operations.

So the following code will solve your problem:

Parse.Cloud.httpRequest({...}).then(function (httpImgFile) {
    var data = {
        base64: httpImgFile.buffer.toString('base64')
    };
    var file = new Parse.File("file", data);
    return file.save();
}).then(function (file) {
  fbPerson.set("profilePicture", file);
  return fbPerson.save();
}).then(function (fbPerson) {
  // fbPerson is saved with the image
});
like image 50
paolobueno Avatar answered Apr 01 '23 07:04

paolobueno