我个人使用canvas.toDataURL()
它生成画布内容的 base64 编码 URL。
之后,我使用以下命令解码了 URLBase64Binary.decode(encodedPng)
获得解码图像后,您可以将其放入表单中并通过 XMLHttpRequest 对象发送所有内容,如下面的代码所示:
// Random boundary defined to separate element in form
var boundary = '----ThisIsTheBoundary1234567890';
// this is the multipart/form-data boundary we'll use
var formData = '--' + boundary + '\r\n';
formData += 'Content-Disposition: form-data; name="source"; filename="' + filename + '"\r\n';
formData += 'Content-Type: ' + mimeType + '\r\n\r\n';
// let's encode our image file
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\nContent-Type: text/html; charset=utf-8\r\n\r\n';
formData += message + '\r\n'
formData += '--' + boundary + '--\r\n';
// Create a POST XML Http Request
var xhr = new XMLHttpRequest();
xhr.open( 'POST', 'https://graph.facebook.com/me/photos?access_token=' + authToken, true );
// Call back function if POST request succeed or fail
xhr.onload = xhr.onerror = function() {
if ( !(xhr.responseText.split('"')[1] == "error") ) {
// If there is no error we redirect the user to the FB post she/he just created
var userID = xhr.responseText.split('"')[7].split('_')[0];
var postID = xhr.responseText.split('"')[7].split('_')[1];
w = window.open('https://www.facebook.com/'+userID+'/posts/'+postID,
'width=1235,height=530');
}
else {
alert("Erreur: "+xhr.responseText);
}
};
xhr.setRequestHeader( "Content-Type", "multipart/form-data; boundary=" + boundary );
// Attach the data to the request as binary
xhr.sendAsBinary( formData );
您可以在文件 maskToFb.html 中查看我的Github 项目的完整工作示例