Facebook JavaScript SDK – Photo upload with FormData

Uploading a photo to Facebook is quite easy if the photo is on a server already. This tutorials explains how to upload a photo to Facebook directly from the device with FormData, without the need to upload in on a server first.

Old school URL upload

var params = {
	//Page Token with publish_pages (to post as Page)
	access_token: pageToken,
	//status message
	message: message,
	//absolute url to the image, must be public
	url: 'https://yourdomain.com/yourimage.jpg'
};

//API call - pageId could also be userId or albumId
FB.api(`/${pageId}/photos`, 'post', params, (response) => {
	if (response && response.error) {
		//upload failed
	} else {
		//upload successful
	}
});

If you do not know how to use the JS SDK in general, i got you there: Facebook API – Login with the JavaScript SDK

You can also do this of user profiles with the publish_actions permission, of course.

Direct File Upload

So what if you just want to use a new photo from your disk, without uploading it to a server first? For that, you can use multiplart/form-data – but it´s a bit tricky because it seems that no one got it to work with the official JavaScript SDK. It works well with the fetch API though, you can also use axios or something else:

Use a file input field to choose the picture and load it with the FileReader object:

const fileReader = new FileReader();
const file = document.getElementById('imageInput').files[0];

fileReader.onloadend = async () => {
	const photoData = new Blob([fileReader.result], {type: 'image/jpg'});
	const formData = new FormData();
	
	formData.append('access_token', pageAccessToken);
	formData.append('source', photoData);
	formData.append('message', 'some status message');

	let response = await fetch(`https://graph.facebook.com/${pageId}/photos`, {
		body: formData,
		method: 'post'
	});
	response = await response.json();
	console.log(response);
};
fileReader.readAsArrayBuffer(file);

Links

5 thoughts on “Facebook JavaScript SDK – Photo upload with FormData”

  1. Hi Andreas,

    Does this create a request that sends json postdata along?

    Currently I have a request where the caption and access_token are added as separate parts. It looks like this:

    https://pastebin.com/U7JMLZW3

    It works. But I’d rather use json postdata and have the resulting request look like this:

    https://pastebin.com/quEDgNTb

    What ‘name’ for the json postdata content-disposition does the js fb sdk use when it creates a request for uploading a photo?

    Sincerely,

    Jay

    1. I am running the posted javascript code myself now, in the hopes that Fiddler would show me the resulting request. Alas, Fiddler isn’t capturing the request!

      Now if only I can find a way to find what request is being fired to Facebook Graph API…

      1. Ok, so I simply used Chrome’s Network tab to view this request. The request is equal to the first pastebin I previously posted… message and access_token in separate bits.

        Apparently, there is no way to post json data along. It’s too bad, but at least I have my answer now.

  2. If I’m right, it looks like this is only for creating post with image on facebook page.
    What if I want to create a post on facebook timeline, in that case I am not suppose to use page ID and neither page accessToken.

    Any kind of response would be highly appreciated.

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.