简体   繁体   中英

Uploading base64 image to Facebook graph API via Javascript/Phonegap

I'm trying to make a "post" request to https://graph.facebook.com/ "+userID+"/photos?access_token="+accessToken

with the 'url' paramter being a base64 data URI.

I got the error "data:base64.... is an interal URL but this is an external request".

I know the pain of not being able to upload a single photo. After sleepless nights and days of research, I finally got it to work with the cordova file-transfer plugin

This solution DOES NOT require Uint8Array or Blobs support ;)

First add the plugin: cordova plugin add org.apache.cordova.file-transfer

Then, use this code (Note that I am using angular.js. Either do not use promises or use a library like rsvp or Q to make your promises):

function postImage(fileURI, message) {

    var deferred = $q.defer();

    var win = function (r) {

        deferred.resolve(r);
    }

    var fail = function (error) {

        deferred.reject(error);
    }

    var options = new FileUploadOptions();
    options.fileKey = "file";
    options.fileName = 'name_of_photo_' + Math.round((+(new Date()) + Math.random()));
    options.mimeType = "image/jpg";

    var params = new Object();
    params.access_token = "your facebook access token ;)";
    params.message = message;
    params.no_story = false;

    options.params = params;

    var ft = new FileTransfer();
    ft.upload(fileURI, "https://graph.facebook.com/v2.0/me/photos", win, fail, options);

    return deferred.promise;
}
  <script src='http://connect.facebook.net/en_US/all.js'></script>
 FB.init({appId: "ur ap id of fb", status: true, cookie: true});
FB.login(function(response) {
       if (response.authResponse) {
         var access_token =   FB.getAuthResponse()['accessToken'];
         FB.api('me/photos', 'post', {
             message: 'posted by xxxx',
             status: 'success',
             access_token: access_token,
             url: 'test.png'
         }, function (response) {

             if (!response || response.error) {
                alert('Error occured');
             } else {
                 alert('Image Posted On Facebook');
             }

         });
       } else {

       }
     }, {scope: 'user_photos,photo_upload,publish_stream,offline_access'});

        },
        error:function(){

        }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM