我正在尝试从 Google Chrome 扩展程序将图像上传到 Picasa,但在构建 POST 时遇到了一些问题。
这是 google 指定用于将图像上传到 Picasa 的协议(链接):
Content-Type: multipart/related; boundary="END_OF_PART"
Content-Length: 423478347
MIME-version: 1.0
Media multipart posting
--END_OF_PART
Content-Type: application/atom+xml
<entry xmlns='http://www.w3.org/2005/Atom'>
<title>plz-to-love-realcat.jpg</title>
<summary>Real cat wants attention too.</summary>
<category scheme="http://schemas.google.com/g/2005#kind"
term="http://schemas.google.com/photos/2007#photo"/>
</entry>
--END_OF_PART
Content-Type: image/jpeg
...binary image data...
--END_OF_PART--
这就是我拼凑起来试图做到这一点,从这里借用代码和扩展“clip-it-good”:
function handleMenuClick(albumName, albumId, data, tab) {
chrome.pageAction.setTitle({
tabId: tab.id,
title: 'Uploading (' + data.srcUrl.substr(0, 100) + ')'
});
chrome.pageAction.show(tab.id);
var img = document.createElement('img');
img.onload = function() {
var canvas = document.createElement('canvas');
canvas.width = img.width;
canvas.height = img.height;
canvas.getContext('2d').drawImage(img, 0, 0);
var dataUrl = canvas.toDataURL();
var dataUrlAdjusted = dataUrl.replace('data:image/png;base64,', '');
var builder = new WebKitBlobBuilder();
builder.append(Base64.decode(dataUrlAdjusted).buffer);
function complete(resp, xhr) {
chrome.pageAction.hide(tab.id);
if (!(xhr.status >= 200 && xhr.status <= 299)) {
alert('Error: Response status = ' + xhr.status +
', response body = "' + xhr.responseText + '"');
}
} // end complete
OAUTH.authorize(function() {
OAUTH.sendSignedRequest(
'http://picasaweb.google.com/data/feed/api/' +
'user/default/albumid/' + albumId,
complete,
{
method: 'POST',
headers: {
'Content-Type': 'multipart/related; boundary=END_OF_PART',
'MIME-version': '1.0'
},
parameters: {
alt: 'json'
},
body: constructContentBody_('title.jpg', 'photo',
builder.getBlob('image/png'),
'image/jpeg', 'lolz')
}
);
});
} // end onload
img.src = data.srcUrl;
}
function constructAtomXml_(docTitle, docType, docSummary) {
var atom = ['<entry xmlns="http://www.w3.org/2005/Atom">',
'<title>', docTitle, '</title>',
'<summary>', docSummary, '</summary>',
'<category scheme="http://schemas.google.com/g/2005#kind"',
' term="http://schemas.google.com/docs/2007#', docType, '"/>',
'</entry>'].join('');
return atom;
};
function constructContentBody_(title, docType, body, contentType, summary) {
var body_ = ['--END_OF_PART\r\n',
'Content-Type: application/atom+xml;\r\n\r\n',
constructAtomXml_(title, docType, summary), '\r\n',
'--END_OF_PART\r\n',
'Content-Type: ', contentType, '\r\n\r\n',
eval(body), '\r\n',
'--END_OF_PART--\r\n'].join('');
return body_;
};
这将返回“错误:响应状态 = 400,响应正文 = “输入时类型无效。”
我不确定 WebKitBlobBuilder 是否有问题,或者我的 POST 格式是否不正确。欢迎大家提出意见!