3

I am trying to post a media to Facebook's page managed my me using the FB.api("/{page_id}/photos") from JavaScript sdk. But I am unable to do so successfully.

How do I encode a local image file as a proper multipart/form-data that can be posted to Facebook.

function onChangeMediaReader() {
  var file = document.getElementById('post-media').files[0];
  reader = new FileReader();
  reader.onload = function() {
    // displays the selected image in canvas.
    document.getElementById('post-media-src').src = reader.result;
    document.getElementById('media-container').style.display = "block";

    // form-data of the selected image for source param.
    formData = new FormData();
    formData.append("source", reader.result);
  }

  if (file) {
    reader.readAsDataURL(file);
  }
}

function publishPost() {
  params.access_token = page_access_token;
  params.message = document.getElementById('post-message').innerHTML;

  if (formData) {
    params.source = formData;
  }

  FB.getLoginStatus(function(response) {
    FB.api(
      '/' + page_id + '/photos',
      "POST",
      params,
      function(response) {
        console.log(response);
      });
  });
}
<form id="image-data" method="post" enctype="multipart/form-data">
  <input type="file" name="source" id="post-media" accept="image/*" onchange="onChangeMediaReader();" />
  <label for="post-media">Upload media</label>
  <br />
  <br />
</form>

<button id="publish-post" onclick="publishPost();">Submit</button>

Response message

"(#324) Requires upload file",
"type: "OAuthException"

IamSravan
  • 87
  • 1
  • 7
  • possible duplicate of [Facebook Graph API - upload photo using JavaScript](http://stackoverflow.com/questions/4999024/facebook-graph-api-upload-photo-using-javascript) – Keenan Lidral-Porter Dec 26 '14 at 06:47
  • @KeenanLidral-Porter I cannot use the "url" param method to post the image to Facebook as that will increase number of network calls that are being made in my application. – IamSravan Dec 26 '14 at 06:55
  • Facebook expects `params.url` to be a string, so your app isn't actually making an additional call. It's just a pointer to a url that tells facebook "Hey, grab the picture from here, I don't actually have the data you want". Using `url` or `source` is still making 1 POST request to the facebook api. [This question](http://stackoverflow.com/questions/18083496/how-to-encode-a-file-from-the-file-system-as-multipart-form-data) may be another helpful reference – Keenan Lidral-Porter Dec 26 '14 at 06:59
  • @KeenanLidral-Porter by extra network call I meant I need to upload the picture to a server to get the url as the images will be in my mobile locally – IamSravan Dec 26 '14 at 07:11

0 Answers0