云代码:从 URL 创建 Parse.File

Cloud Code: Creating a Parse.File from URL

我正在开发一个 Cloud Code 函数,该函数使用 facebook 图 API 来检索用户个人资料图片。所以我可以访问正确的图片 URL 但我无法从这个 URL.

创建一个 Parse.File

这正是我正在尝试的:

    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");
        }
    });

并返回以下内容:

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)

想法?

我现在遇到了这个完全相同的问题。出于某种原因,这个问题已经在 Google 的 parsefile from httprequest buffer!

结果中排在首位

Parse.File documentation

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

我认为对于 CloudCode,最简单的解决方案是 2。早些时候让我绊倒的是我没有注意到它期望格式为 { base64: {{your base64 encoded data here}} }.

Object

此外,Parse.Files 只能在保存后设置为 Parse.Object(此行为也存在于所有客户端 SDK 上)。我强烈建议使用 API 的 Promise 版本,因为它可以更轻松地编写此类异步操作。

所以下面的代码将解决您的问题:

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
});