4

我正在画布中合成图像,通过使用和修剪附加信息来获取base64图像数据。canvas.toDataURL('png')

 var dataUrl = canvas.toDataURL('png');
 var escapedBase64Data = dataUrl.replace("data:image/png;base64,","");

之后,我尝试使用以下方式发布到 Facebook:

FB.api('/me/photos', 'post', { source:data});

照片(https://developers.facebook.com/docs/reference/api/user/)具有源属性。您将在此处放置照片的数据内容 ( multipart/form-data )。

我通过指定标头将我的base64编码数据转换为 multipart/form-data 。

结果如下所示:

--0.2242348059080541
Content-Disposition: file; name="file"; filename="image.png"
Content-Type: image/png
Content-Transfer-Encoding: base64

iVBORw0KGgoAAAANSUhEUgAAAfQAAAH0CAYAAADL1t+KAAAbBElEQVR4Xu3dP4jre0LG4V2xsFVYEKy
...    
QAAAABJRU5ErkJggg==

--0.2242348059080541--

完成 FB api 调用后,我收到以下错误:

Object {message: "(#324) Requires upload file", type: "OAuthException", code: 324} 

有什么建议么?

谢谢

4

2 回答 2

1

这是一个工作代码示例:

var boundary = '----ThisIsTheBoundary1234567890';
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 += f.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() {
    // error managment
};
xhr.setRequestHeader("Content-Type", "multipart/form-data; boundary=" + boundary);

//Send the request
xhr.sendAsBinary(formData);
于 2013-05-02T16:18:21.857 回答
0

这是一个简单的解决方案:

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'
    });
}
const upload = async (response) => {
    let canvas = document.getElementById('canvas');
    let dataURL = canvas.toDataURL('image/jpeg', 1.0);
    let blob = dataURItoBlob(dataURL);
    let formData = new FormData();
    formData.append('access_token', response.authResponse.accessToken);
    formData.append('source', blob);

    let responseFB = await fetch(`https://graph.facebook.com/me/photos`, {
        body: formData,
        method: 'post'
    });
    responseFB = await responseFB.json();
    console.log(responseFB);
};
document.getElementById('upload').addEventListener('click', () => {
    FB.login((response) => {
        //TODO check if user is logged in and authorized publish_actions
        upload(response);
    }, {scope: 'publish_actions'})
})

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

于 2018-04-06T23:44:16.167 回答