如何使用javascript从gmail api下载附件?

时间:2015-11-19 19:28:16

标签: javascript gmail-api

我正在创建一个使用gmail api阅读我的电子邮件的网络应用程序。所有方法都在工作(users.messages.list,users.messages.get等),并在console.log和我的页面HTML中显示。有一点我注意到我必须使用 atob 来解码 body.data 并插入我的HTML中。现在我必须下载或阅读附件以获取例如 file.docx ,并且我在回调后使用此示例here我注意到我也必须解码,但是如果我这样做,没有下载或阅读的链接,只有微软的一些代码。如果我复制此代码并创建一个文档并粘贴它,则表示该文件已损坏。

我的代码:

function getAttachments(messageID, parts, callback) {
    //console.log(parts);
    var attachId = parts.body.attachmentId;
    var request = gapi.client.gmail.users.messages.attachments.get({
        'id': attachId,
        'messageId': messageID,
        'userId': 'me'
    });
    request.execute(function (attachment) {
        callback(parts.filename, parts.mimeType, attachment);
    });
}

if (att.length > 0) {
    for (var i in att) {
        getAttachments(response.id, att[i], function (filename, mimeType, attachment) {
            console.clear();
            console.log(filename, mimeType, attachment);
            console.log(atob(attachment.data.replace(/-/g, '+').replace(/_/g, '/')));
            inline.append('<a href="" style="display: block">' + filename + '</a>');
        });
    }
}

更新

我找到了解决方案here

1 个答案:

答案 0 :(得分:3)

尝试此解决方案。

<强> HTML

<a id="download-attach" download="filename"/>

<强> JS

function getAttachments(messageID, parts, callback) {
    var attachId = parts.body.attachmentId;
    var request = gapi.client.gmail.users.messages.attachments.get({
      'id': attachId,
      'messageId': messageID,
      'userId': 'me'
    });
    request.execute(function (attachment) {
      callback(parts.filename, parts.mimeType, attachment);
    });
  }

if (att.length > 0) {
    for (var i in att) {
       getAttachments(response.id, att[i], function (filename, mimeType, attachment) {

       let dataBase64Rep = attachment.data.replace(/-/g, '+').replace(/_/g, '/')

       let urlBlob = b64toBlob(dataBase64Rep, mimeType, attachment.size)

       let dlnk = document.getElementById('download-attach')
       dlnk.href = urlBlob
       dlnk.download = filename
       dlnk.click()
       URL.revokeObjectURL(urlBlob)
   }
}

function b64toBlob (b64Data, contentType, sliceSize) {
  contentType = contentType || ''
  sliceSize = sliceSize || 512

  var byteCharacters = atob(b64Data)
  var byteArrays = []

  for (var offset = 0; offset < byteCharacters.length; offset += sliceSize) {
    var slice = byteCharacters.slice(offset, offset + sliceSize)

    var byteNumbers = new Array(slice.length)
    for (var i = 0; i < slice.length; i++) {
      byteNumbers[i] = slice.charCodeAt(i)
    }

    var byteArray = new Uint8Array(byteNumbers)

    byteArrays.push(byteArray)
  }

  var blob = new Blob(byteArrays, {type: contentType})
  let urlBlob = URL.createObjectURL(blob)
  return urlBlob
}