Javascript Facebook API POST multipart/form-data

Javascript Facebook API POST multipart/form-data

本文关键字:form-data multipart POST Facebook API Javascript      更新时间:2023-09-26

在过去的几天里,我一直被这个问题完全难住了。如果有人能指出我正确的方向,我将不胜感激!我一直在试图弄清楚如何通过Facebook的图形api发布图像。

我有一张通过他们的图形 API 从 Facebook 下载的图像,该图像正确显示在画布元素中。我正在通过在上面绘制文本来修改此元素,然后想将其上传回Facebook。我被困在上传上。

以下是我查看过的链接,这些链接很有帮助,但我仍然卡住了:

Facebook Graph API - 使用 JavaScript 上传照片讨论使用多部分/表单数据通过发布请求上传到Facebook。

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

这是我用来尝试将图像发布到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
}

记录了表单数据,我粘贴了下面的输出:

------这是边界1234567890
Content-Disposition: form-data; name="source"; filename="MemeImage.png"
内容类型:图像/png

------这是边界1234567890
内容处置:表单数据;名称="消息"

发布模因图片
------这是边界1234567890--

尝试替换

for ( var i = 0; i < imageData.length; ++i )
{
    formData += String.fromCharCode( imageData[ i ] & 0xff );
}

formData += imageData;

这可以通过更简单的方式实现,只需使用以下代码将 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/