繁体   English   中英

Javascript Facebook API POST multipart / form-data

[英]Javascript Facebook API POST multipart/form-data

在过去的几天里,我对这个问题感到非常难过。 如果有人能指出我正确的方向,我会很感激! 我一直试图找出如何通过facebooks graph api发布图像。

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

以下是我看过的有用的链接,但我仍然感到困惑:

Facebook Graph API - 使用JavaScript上传照片使用 multipart / form-data 上传照片,使用发布请求上传到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
}

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

------ ThisIsTheBoundary1234567890
内容处理:表格数据; NAME = “源”; 文件名= “MemeImage.png”
内容类型:image / png

------ ThisIsTheBoundary1234567890
内容处理:表格数据; 名称=“消息”

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

尝试更换

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/

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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