Skip to content

Instantly share code, notes, and snippets.

@dansimco
Created January 2, 2013 04:27
Show Gist options
  • Save dansimco/4432191 to your computer and use it in GitHub Desktop.
Save dansimco/4432191 to your computer and use it in GitHub Desktop.
Posts a photo to a users profile, creating a gallery where needed.
/*global FB, alert, console */
//Usage
// uploadPhotoToFacebook({
// caption: 'A Picture',
// url: 'http://lorempixel.com/400/300/',
// album: 'JS API',
// album_description: "An album of pictures",
// onSuccess: function(){
// alert('hooray');
// },
// onFailure: function(){
// alert('oh no!');
// }
// });
function uploadPhotoToFacebook(params) {
"use strict";
var self = {}, album_id = false, authResponse;
self.postPhoto = function () {
//Post Photo in album
FB.api('/' + album_id + '/photos', 'post', {
message: params.caption,
url: params.url
},
function (response) {
if (!response || response.error) {
if (params.onFailure) {
params.onFailure();
}
} else {
if (params.onSuccess) {
params.onSuccess(response.id);
}
}
});
};
FB.login(function (response) {
if (response.authResponse) {
authResponse = response.authResponse;
//Check for existing albums
FB.api('/me/albums?access_token=' + authResponse.accessToken, function (response) {
var album;
for (album in response.data) {
if (response.data[album].name === params.album) {
album_id = response.data[album].id;
}
}
if (album_id) {
self.postPhoto();
} else {
//Create Album
FB.api('/me/albums?access_token=' + authResponse.accessToken, 'post',
{
name: params.album,
message: params.album_description || ""
},
function (response) {
album_id = response.id;
self.postPhoto();
});
}
});
}
}, {scope: 'publish_stream, user_photos'});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment