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:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 | $( '#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({ 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 “open_gestmxg_user@tfbnw.net” and password “123Qweasd”.
Notes: to upload photos you will need to create a facebook application with permission “publish_actions” and “user_photos”.
After two days trying to find a solution I finally found this post. Still working fine with the last API version (3.3). Thank you!!