Javascript Facebook API POST multipart / form-data

时间:2014-04-02 05:01:58

标签: javascript facebook facebook-graph-api facebook-javascript-sdk

过去几天我一直对这个问题感到十分困惑。如果有人能指出我正确的方向,我会很感激!我一直试图弄清楚如何通过facebooks graph api发布图片。

我通过图形API从Facebook下载了一个图像,该图形API正确地显示在画布元素中。我通过在其上绘制文本来修改此元素,然后将其上传回Facebook。我对上传感到困惑。

以下是我看过哪些有用的链接,但我仍然坚持:

Facebook Graph API - upload photo using JavaScript 讨论使用multipart / form-data使用帖子请求上传到Facebook。

https://gist.github.com/andyburke/1498758 用于创建多部分表单数据并向Facebook发送请求以发布图像的代码。

这是我用来尝试将图片发布到脸书

的代码
if ( XMLHttpRequest.prototype.sendAsBinary === undefined ) {
    XMLHttpRequest.prototype.sendAsBinary = function(string) {
        var bytes = Array.prototype.map.call(string, function(c) {
            return c.charCodeAt(0) & 0xff;
        });
        //this.send(new Uint8Array(bytes).buffer); //depreciated warning
        this.send(new Uint8Array(bytes));
    };
}

// This function takes an array of bytes that are the actual contents of the image file.
// In other words, if you were to look at the contents of imageData as characters, they'd
// look like the contents of a PNG or GIF or what have you.  For instance, you might use
// pnglib.js to generate a PNG and then upload it to Facebook, all from the client.
//
// Arguments:
//   authToken - the user's auth token, usually from something like authResponse.accessToken
//   filename - the filename you'd like the uploaded file to have
//   mimeType - the mime type of the file, eg: image/png
//   imageData - an array of bytes containing the image file contents
//   message - an optional message you'd like associated with the image

function PostImageToFacebook( authToken, filename, mimeType, imageData, message )
{
    console.log("filename " +  filename);
    console.log("mimeType " + mimeType);
    console.log("imageData " + imageData);
    console.log("message " + message);

    // this is the multipart/form-data boundary we'll use
    var boundary = '----ThisIsTheBoundary1234567890';

    // let's encode our image file, which is contained in the var
    var formData = '--' + boundary + '\r\n'
    formData += 'Content-Disposition: form-data; name="source"; filename="' + filename + '"\r\n';
    formData += 'Content-Type: ' + mimeType + '\r\n\r\n';
    for ( var i = 0; i < imageData.length; ++i )
    {
        formData += String.fromCharCode( imageData[ i ] & 0xff );
    }
    formData += '\r\n';
    formData += '--' + boundary + '\r\n';
    formData += 'Content-Disposition: form-data; name="message"\r\n\r\n';
    formData += message + '\r\n'
    formData += '--' + boundary + '--\r\n';

    var xhr = new XMLHttpRequest();
    xhr.open( 'POST', 'https://graph.facebook.com/me/photos?access_token=' + authToken, true );
    xhr.onload = xhr.onerror = function() {
        console.log( xhr.responseText );
    };
    xhr.setRequestHeader( "Content-Type", "multipart/form-data; boundary=" + boundary );
    xhr.sendAsBinary( formData );
    console.log(formData);
}

对PostImageToFacebook函数的调用导致以下错误:

{
   "error": {
      "type": "Exception",
      "message": "Your photos couldn't be uploaded. Photos should be less than 4 MB and saved as JPG, PNG, GIF or TIFF files.",
      "code": 1366046
}

我记录下面粘贴的输出formData:

  

------ ThisIsTheBoundary1234567890   
内容 - 处置:表格数据;命名=&#34;源&#34 ;;文件名=&#34; MemeImage.png&#34;   
内容类型:image / png   

------ ThisIsTheBoundary1234567890   
内容 - 处置:表格数据;命名=&#34;消息&#34;   

发布模因图像   
------ ThisIsTheBoundary1234567890 -

1 个答案:

答案 0 :(得分:0)

这可以用一种不太复杂的方式实现,只需将Canvas图像转换为具有以下代码的博客:

const dataURItoBlob = (dataURI) => {
    let byteString = atob(dataURI.split(',')[1]);
    let ab = new ArrayBuffer(byteString.length);
    let ia = new Uint8Array(ab);
    for (let i = 0; i < byteString.length; i++) {
        ia[i] = byteString.charCodeAt(i);
    }
    return new Blob([ia], {
        type: 'image/jpeg'
    });
}

无需自己设置所有这些标头,只需使用带有FormData的博客:

formData.append('source', blob);

来源:http://www.devils-heaven.com/facebook-javascript-sdk-photo-upload-from-canvas/