3

I am trying to upload a photo to facebook album with this javaascript code.

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

Can someone help me with this code. This code is not returning anything.

nishantcm
  • 935
  • 5
  • 14
  • 28

3 Answers3

4

Assuming you want to do this in pure JavaScript/JQuery - you'll need to use an iframe as the target of a form, there is a caveat - you will not be able to use the return data (the ID / success of the call) because of the same origin policy.

First create a form that will hold the file input and any other variables you wish to set:

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

Here is the main function used which creates an iframe, points the form to use it, and then retrieves the latest photo from the album using 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();

}   

At runtime you will presumably know the albumObjectID from a previous call, and have the access token from the session object that is returned by login or session onauthchange.

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

Obviously this isn't production code, there are a few things you can do to improve it's reliability (like checking the width, height, caption & tags of the submitted image to the latest image). Checking the latest image before & after the attempted upload etc.

PS: Watch out for the albumObjectID vs albumID, they are different however both can be obtained using some simple FQL queries. (eg: SELECT aid, object_id, can_upload, name FROM album WHERE owner = me() AND name = "My Album Name")

Hope this helps.
CameraSchoolDropout

  • This is the best workaroud I've found. Still, even though I'm able to submit the photo using something similar to this technique, I'm later unable to check the response to validate the upload. Any though on how to do it? – tiagoboldt May 23 '11 at 12:37
  • if it's a make or break scenario I would either: a) upload the file to my own server and then have it perform the transfer (essentially using your server on the same domain as a proxy). b) use an optimistic concurrency model by querying the album photos before and after the upload, if there has been a change it's very likely the upload was successful - this has the advantage of being achievable purely in javascript. good luck. – CameraSchoolDropout May 24 '11 at 12:20
  • I've personally have setup a django server to handle this part. If anyone follows this thread, there's no viable way to guarantee the upload success, just by requesting and see if there's something there, as @CameraSchoolDropout suggested. But that sucks. – tiagoboldt May 27 '11 at 09:00
  • You could upload the photo and make a FQL-request after it finished uploading to check if the photo exists, if it didn't you know something went wrong – xorinzor Jan 14 '12 at 15:38
3

You're not far from the right query.

first, make sure your initiating the js sdk, and requesting permissions to post.

then, your two fields are message and 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);
    }
}); 
AE Grey
  • 368
  • 4
  • 14
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);
    }
  });
}
RAFEL
  • 1
  • 2