将图片从Chrome扩展程序上传到Picasa

时间:2011-07-19 18:49:24

标签: javascript webkit google-chrome-extension picasa

我正在尝试从Google Chrome扩展程序将图片上传到Picasa,但在构建POST时遇到了一些麻烦。

这是Google指定用于将图片上传到Picasa(link)的协议:

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--

这就是我拼凑起来试图做到这一点,借用here的代码和扩展名“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是不正确的。欢迎任何建议!

1 个答案:

答案 0 :(得分:2)

除了我通过FileReader.readAsBinaryString(file)加载文件外,我的多部分方法看起来几乎一样。但是,Picasa会针对BMP文件返回“非图像”(对于JPG / PNG文件)或“不是有效图像”的错误请求。

如果您直接发布图片,它确实有效(201 Created)。以下代码适用于我:

function upload_image(file, albumid) {
// Assuming oauth has been initialized in a background page
var oauth = chrome.extension.getBackgroundPage().oauth; 
var method = 'POST';
var url = 'https://picasaweb.google.com/data/feed/api/user/default/albumid/' + albumid;
var xhr = new XMLHttpRequest();
xhr.open(method, url, true);
xhr.setRequestHeader("GData-Version", '3.0');
xhr.setRequestHeader("Content-Type", file.type);
xhr.setRequestHeader("Authorization", oauth.getAuthorizationHeader(url, method, ''));
xhr.onreadystatechange = function(data) {
    if (xhr.readyState == 4) {
        on_image_sent(data, xhr);
    }
};
xhr.send(file);

其中file是来自FileIO API的HTML5文件对象。