Cloud Code: Creating a Parse.File from URL

心已入冬 提交于 2019-12-05 19:41:57

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
});
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!