Phonegap / Cordova上传照片到graph.facebook - 需要上传文件

时间:2014-08-10 20:00:38

标签: javascript android facebook cordova facebook-graph-api-v2.0

我正在使用facebook图形api的v2.0版本,我正在尝试将图片上传到v2.0 / me / photos,但遗憾的是我收到此错误(#324) Requires upload file,这很奇怪,因为我有publish_actions权限,文档说这就是我所需要的。

我正在使用phonegap,因此正常的JS SDK对我不起作用而且cordova-facebook-plugin使得cordova失败了它的构建(按照至少5个论坛/博客的说明,没有任何效果),这就是为什么我我正在为我的应用程序使用纯XMLHTTPRequests和AJAX请求。一切正常(我可以发布消息到用户的墙上,登录就好了),除了这个图片上传。这是我正在使用的功能(数据是图像的URI):

function postImage(data, message) {

    var imageData = data.replace('data:image/jpeg;base64,', ''),
        mimeType = 'image/jpg',
        authToken = tokenStore['acess.token'],
        filename = 'bikeDice_screenshot_' + Math.round((+(new Date()) + Math.random())),
        deferred = $q.defer();

    try {
        var blob = dataURItoBlob(imageData, mimeType);
    } catch (e) {
        alert(e);
    }

    var fd = new FormData();
    fd.append("access_token", authToken);
    fd.append("source", '%7B' + blob + '%7D');
    fd.append("message", message);
    fd.append("no_story", false);

    try {

        $.ajax({
            url: 'https://graph.facebook.com/v2.0/me/permissions?access_token=' + authToken,
            type: 'GET',
            success: function (data) {
                alert(JSON.stringify(data));
            },
            error: function (err) {
                alert(err);
            }
        });

        $.ajax({
            url: "https://graph.facebook.com/v2.0/me/photos?access_token=" + authToken,
            type: "POST",
            data: fd,
            processData: false,
            contentType: false,
            cache: false,
            success: function (data) {
                console.log("success " + data);

                deferred.resolve(data);
            },
            error: function (shr, status, data) {

                alert(JSON.stringify(shr));
                deferred.reject(data);
            },
            complete: function () {
                console.log("Ajax Complete");
            }
        });

    } catch (e) {
        alert('error in ajax request ');
        alert(JSON.stringify(e));
    }

    function dataURItoBlob(dataURI, mime) {
        // convert base64 to raw binary data held in a string
        // doesn't handle URLEncoded DataURIs

        var byteString = window.atob(dataURI);
        // separate out the mime component


        // write the bytes of the string to an ArrayBuffer
        //var ab = new ArrayBuffer(byteString.length);
        var ia = new Uint8Array(byteString.length);
        for (var i = 0; i < byteString.length; i++) {
            ia[i] = byteString.charCodeAt(i);
        }

        // write the ArrayBuffer to a blob, and you're done

        try {
            var blob = new Blob([ia], {
                type: mime
            });
        } catch (e) {
            try {
                window.BlobBuilder = window.BlobBuilder || window.WebKitBlobBuilder || window.MozBlobBuilder || window.MSBlobBuilder;

                if (e.name == 'TypeError' && window.BlobBuilder) {
                    var bb = new BlobBuilder();
                    bb.append([ia.buffer]);
                    var blob = bb.getBlob(mime);
                    var bb = new BlobBuilder();

                } else if (e.name == "InvalidStateError") {
                    // InvalidStateError (tested on FF13 WinXP)
                    var blob = new Blob([ia.buffer], {
                        type: mime
                    });
                } else {
                    alert('Blob constructor unsupported entirely! ');
                }

            } catch (e) {
                alert(e);
            }
        }

        return blob;
    }


    return deferred.promise
};

P.S。:在智能手机上,如果在try / catch块中脚本总是这样:

if (e.name == 'TypeError' && window.BlobBuilder) {
    var bb = new BlobBuilder();
    bb.append([ia.buffer]);
    var blob = bb.getBlob(mime);
    var bb = new BlobBuilder();

}

P.S.2:我尝试将&upload_file=true添加到帖子请求的网址中,真的没有运气......; /

1 个答案:

答案 0 :(得分:4)

这是我发现的解决方案,使用cordova文件传输插件,就像带有数据URI的魅力一样:

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;
}

但首先,使用cordova plugin add org.apache.cordova.file-transfer

将插件添加到cordova