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

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:

Links

4 thoughts on “Facebook JavaScript SDK – Photo upload with FormData

  1. Jay says:

    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

    • Jay says:

      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…

      • Jay says:

        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.

Leave a Reply

Your email address will not be published.

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