Facebook Graph API – upload photo using JavaScript from local computer

Hi everyone, recently I encountered a problem with uploading photos to Facebook using Graph API with JavaScript. And there were no working solutions on Stack Overflow nor some example in official Facebook documentation.

So I have to figure out something, and here is how I do it:


$('#button_upload').click(function (e) {
   e.preventDefault();

    // Get file object from file input
    var file = $('#input_file')[0].files[0];

    // If file is selected
    if (file) {
        // We will use FileReader
        var reader = new FileReader();
        // And and onload callback when file data loaded
        reader.onload = function (e) {
            // This is array buffer of the file
            var arrayBuffer = e.target.result;
            // And blob object of the file
            var blob = new Blob([arrayBuffer], { type: file.type });

            // We will use FormData object to create multipart/form request
            var data = new FormData();
            data.append('access_token', FB.getAccessToken());
            data.append('source', blob);
            data.append('message', $('#input_description').val());

            $('#uploading').show();

            // Send the request manually with jQeury
            $.ajax({
                url: 'https://graph.facebook.com/me/photos?access_token=' + FB.getAccessToken(),
                type: 'POST',
                data: data,
                processData: false,
                contentType: false,
                cache: false,
                success:function (data) {
                    $('#status').append('<p>Photo was successfully uploaded, object id is: ' + data.id + '</p>');
                    console.log(data)
                },
                error:function (data) {
                    console.log(data);
                },
                complete: function () {
                    $('#uploading').hide();
                }
            });

        };
        // Read file as array buffer to create blob object
        reader.readAsArrayBuffer(file);
    }
});

Try out this working example facebook-upload-photos you will need to use test user “[email protected]” and password “123Qweasd”.

Notes: to upload photos you will need to create a facebook application with permission “publish_actions” and “user_photos”.