Facebook新的javascript sdk-用它上传照片!

时间:2010-11-24 08:05:19

标签: facebook facebook-graph-api facebook-javascript-sdk

我正在尝试使用此javascript代码将照片上传到Facebook相册。

FB.api('/me/photos', 'post', {    access_token: GetToken(),
                            name: 'uploaded photo',
                            source: '@http://example.com/example.jpg' }, 
            function(response) {
                if (!response || response.error) {
                    alert('Error occured ' + response.error.message);
                } else {
                    alert('Post Id: ' + response.id);
                }
            });

有人可以帮我解决这个问题。这段代码没有返回任何内容。

3 个答案:

答案 0 :(得分:4)

假设您想在纯JavaScript / JQuery中执行此操作 - 您需要使用iframe作为表单的目标,有一个警告 - 您将无法使用返回数据(ID /成功) (因为相同的原产地政策)。

首先创建一个表单来保存文件输入和您想要设置的任何其他变量:

<form id="upload-photo-form">
    <input name="source" id="source" size="27" type="file" />
    <input name="message" id="message" type="text" value="message example please ignore" />
</form>

这是使用的主要功能,它创建一个iframe,指向表单使用它,然后使用FQL从相册中检索最新的照片。

function fileUpload(form, action_url, div_id) {
    // Create an iframe 
    var iframe = document.createElement("iframe");
    iframe.setAttribute('id', "upload_iframe");
    iframe.setAttribute('name', "upload_iframe");
    iframe.setAttribute('width', "0px");
    iframe.setAttribute('height', "0px");
    iframe.setAttribute('border', "0");
    iframe.setAttribute('style', "width: 0; height: 0; border: none;");

    // Add to document.
    form.parentNode.appendChild(iframe);
    window.frames['upload_iframe'].name = "upload_iframe";

    iframeId = document.getElementById("upload_iframe");

    // Add event to detect when upload has finished
    var eventHandler = function () {

        if (iframeId.detachEvent)
        {
            iframeId.detachEvent("onload", eventHandler);
        }
        else
        {
            iframeId.removeEventListener("load", eventHandler, false);
        }

        setTimeout(function() {
            try
            {
                $('#upload_iframe').remove();
            } catch (e) {

            }
        }, 100);

        FB.api({
            method: 'fql.query',
            query: 'SELECT src_big,pid,caption,object_id FROM photo WHERE aid= "' + albumID + '" ORDER BY created DESC LIMIT 1'
            },
            function(response) {
                console.log(response);
            }
        );

    }

    if (iframeId.addEventListener)
        iframeId.addEventListener('load', eventHandler, true);
    if (iframeId.attachEvent)
        iframeId.attachEvent('onload', eventHandler);

    // Set properties of form...
    form.setAttribute('target', 'upload_iframe');
    form.setAttribute('action', action_url);
    form.setAttribute('method', 'post');
    form.setAttribute('enctype', 'multipart/form-data');
    form.setAttribute('encoding', 'multipart/form-data');

    // Submit the form...
    form.submit();

}   

在运行时,您可能会知道前一次调用中的albumObjectID,并且具有登录或会话onauthchange返回的会话对象的访问令牌。

var url = 'https://graph.facebook.com/' + albumObjectID + '/photos?access_token=' +  accessToken;
fileUpload($('#upload-photo-form')[0], url, $('#upload-photo-div')[0]);`

显然这不是生产代码,您可以采取一些措施来提高其可靠性(例如检查提交图像的宽度,高度,标题和标签到最新图像)。在&amp;之前检查最新图像尝试上传后等。

PS:注意albumObjectID vs albumID,它们是不同的,但是两者都可以使用一些简单的FQL查询获得。 (例如:SELECT aid, object_id, can_upload, name FROM album WHERE owner = me() AND name = "My Album Name"

希望这有帮助。
CameraSchoolDropout

答案 1 :(得分:3)

你离正确的查询不远。

首先,确保您启动js sdk,并请求发布权限。

然后,您的两个字段是消息和URL:

var data = array();
data['message'] = 'hello world';
data['url'] = 'http://google.com/moo.jpg';

FB.api('/me/photos', 'post', data, function(response){
    if (!response || response.error) {
        //alert('Error occurred');
    } else {
        //alert('Post ID: ' + response.id);
    }
}); 

答案 2 :(得分:0)

// UPLOAD A LOCAL IMAGE FILE, BUT THIS CAN NOT BE DONE WITHOUT USER'S MANUAL OPERATION BECAUSE OF SECURITY REASONS
function fileUpload() {
  FB.api('/me/albums', function(response) {
    var album = response.data[0]; // Now, upload the image to first found album for easiness.
    var action_url = 'https://graph.facebook.com/' + album.id + '/photos?access_token=' +  accessToken;
    var form = document.getElementById('upload-photo-form');
    form.setAttribute('action', action_url);

    // This does not work because of security reasons. Choose the local file manually.
    // var file = document.getElementById('upload-photo-form-file');
    // file.setAttribute('value', "/Users/nseo/Desktop/test_title_03.gif")

    form.submit();
  });
}
// POST A IMAGE WITH DIALOG using FB.api
function postImage1() {
  var wallPost = {
    message: "Test to post a photo",
    picture: "http://www.photographyblogger.net/wp-content/uploads/2010/05/flower29.jpg"
  };
  FB.api('/me/feed', 'post', wallPost , function(response) {
    if (!response || response.error) {
      alert('Failure! ' + response.status + ' You may logout once and try again');
    } else {
      alert('Success! Post ID: ' + response);
    }
  });
}