Cloud Code: Creating a Parse.File from URL
Asked Answered
L

1

5

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?

Lightfooted answered 15/11, 2015 at 21:29 Comment(0)
I
8

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
});
Illegitimacy answered 17/11, 2015 at 11:33 Comment(3)
Thanks Paolo, worked well. What about helping in this one: #33762891 Valeu! HUELightfooted
You can set an unsaved PFFile on an iOS PFObject, and have it be saved when you save the PFObject.Billie
This was a lifesaver for me . I was trying to get byte data back to the android client and this worked perfectly. Back on android i extracted the like this. byte[] imgBytes = Base64.decode(object, Base64.DEFAULT);Throe

© 2022 - 2024 — McMap. All rights reserved.