使用 Javascript SDK 批量上传多张照片到 Facebook

Upload multiple photos in batch to Facebook using Javascript SDK

我可以通过 URL 将单张照片上传到 Facebook,但我无法使用批量上传。我收到 (#324) Requires Upload File 未捕获的异常。我确保用户已登录,当我查看批处理负载 (batchJson) 时它看起来没问题。

明确地说,如果我删除所有与批处理相关的设置代码,并在 FB.api 调用中将 "batch" : batchJson 替换为单个 "url": photoUrl,则代码有效。

这是我的代码。 TIA 了解我的错误:

var message = $("#message-fb").val();
var batchItems = [];
var photoUrl = "";

$(".photo-selected").each(function () {        
    photoUrl = $(this).data('content');
    item = {};
    item['method'] = 'POST';
    item['relative_url'] = 'me/photos';
    item['url'] = encodeURI(photoUrl);
    item['caption'] = message;        
    batchItems.push(item);
});
batchJson = JSON.stringify(batchItems);

alert(batchJson);

FB.getLoginStatus(function (response) {
    if (response.status === 'connected') {
        // Already logged in and authorized
        FB.api(
            "/",
            "POST",
            {
                "batch": batchJson
            },
            function (response) {
                if (response && !response.error) {
                    /* successful upload */
                    alert('Photos uploaded to Facebook (nl) - ' + JSON.stringify(response));
                }
                if (response && response.error) {
                    /* Provide error info during testing */
                    alert('Sorry, there was a problem uploading your photo to Facebook - ' + JSON.stringify(response));
                }
            });
    } else {
        // Need to login and authorize
        FB.login(function () {
            FB.api(
                "/",
                "POST",
                {
                    'batch': batchJson
                },
                function (response) {
                    if (response && !response.error) {
                        /* successful upload */
                        alert('Photos uploaded to Facebook - ' + JSON.stringify(response));
                    }
                    if (response && response.error) {
                        /* Provide error info during testing */                            
                        alert('Sorry, there was a problem uploading your photo to Facebook - ' + JSON.stringify(response));
                    }
                });
        }, { scope: 'publish_actions' });
    }
});

编辑:以下是使用@CBroe 的回答所做的相关更改:

$(".photo-selected").each(function () {        
    var photoUrl = $(this).data('content');
    var item = {};
    item['method'] = 'POST';
    item['relative_url'] = 'me/photos';
    var itemUrl = encodeURI(photoUrl);
    var itemCaption = encodeURIComponent(message);
    item['body'] = "caption=" + itemCaption + "&url=" + itemUrl;
    batchItems.push(item);
});
batchJson = JSON.stringify(batchItems);

您发送的 urlcaption 参数与 methodrelative_url 处于同一“级别”——它们需要放在 body 属性 然而。并且该字段的内容必须以与通过表单的实际 POST 请求的编码方式相同的方式进行编码(就像 URL 查询字符串,param1=value1&param2=value2)。