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

时间:2015-04-30 01:43:37

标签: javascript facebook facebook-javascript-sdk

我可以通过网址将单张照片上传到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' });
    }
});
编辑:以下是使用@Cabroe答案的相关更改:

$(".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);

1 个答案:

答案 0 :(得分:1)

您要发送与urlcaption相同“级别”的methodrelative_url个参数 - 它们需要放在body内但是财产。并且该字段的内容必须以与编码实际POST请求相同的方式进行编码(就像URL查询字符串param1=value1&param2=value2)。