axios 通过NodeJS从Gmail下载附件

tvz2xvvm  于 5个月前  发布在  iOS
关注(0)|答案(1)|浏览(81)

我有一个基于NodeJS的自动化脚本,它从Gmail获取数据。但是我的附件是PDF,当我的代码下载到我的本地文件夹时,它的内容被转换为字符串。任何解决这个问题的建议都将非常有帮助。
这是我的附件下载功能,它将永远是PDF。

function downloadAttachment(attachmentId, filename, messageId, callback) {
    axios.get(`https://gmail.googleapis.com/gmail/v1/users/me/messages/${messageId}/attachments/${attachmentId}`, {
        responseType: 'arraybuffer',
        headers: {
            Authorization: `Bearer ${token.access_token}`,
        },
    })
        .then(response => {
            fs.writeFileSync(filename, Buffer.from(response.data, 'base64'));
            console.log(`Attachment saved locally: ${filename}`);
            callback();
        })
        .catch(error => {
            console.error('Error downloading attachment:', error);
        });
}

字符串

nwlqm0z1

nwlqm0z11#

当你的展示脚本被修改时,下面的修改怎么样?

修改脚本1:

在这种情况下,使用responseType: "arraybuffer"

function downloadAttachment(attachmentId, filename, messageId, callback) {
  axios
    .get(
      `https://gmail.googleapis.com/gmail/v1/users/me/messages/${messageId}/attachments/${attachmentId}`,
      {
        responseType: "arraybuffer",
        headers: {
          Authorization: `Bearer ${token.access_token}`,
        },
      }
    )
    .then((response) => {
      
      // --- I modified the below script.
      const str = new TextDecoder().decode(new Uint8Array(response.data));
      const { data } = JSON.parse(str);
      fs.writeFileSync(filename, Buffer.from(data, "base64"));
      // ---
      
      console.log(`Attachment saved locally: ${filename}`);
      callback();
    })
    .catch((error) => {
      console.error("Error downloading attachment:", error);
    });
}

字符串

修改脚本二:

在这种情况下,使用responseType: "json"。当使用responseType: "json"时,脚本变得简单一点。

function downloadAttachment(attachmentId, filename, messageId, callback) {
  axios
    .get(
      `https://gmail.googleapis.com/gmail/v1/users/me/messages/${messageId}/attachments/${attachmentId}`,
      {
        responseType: "json",
        headers: {
          Authorization: `Bearer ${token.access_token}`,
        },
      }
    )
    .then(({ data: { data } }) => {
      fs.writeFileSync(filename, Buffer.from(data, "base64"));
      console.log(`Attachment saved locally: ${filename}`);
      callback();
    })
    .catch((error) => {
      console.error("Error downloading attachment:", error);
    });
}

  • 当我测试这个修改后的脚本时,我确认附件文件可以下载。
  • 从数组缓冲区解码的数据是一个类似{"size": 123, "data": "base64 data"}的对象。因此,为了将数据保存为文件,需要解码base64数据。请注意这一点。

参考:

相关问题