通过 NodeJS 从 Gmail 下载附件

问题描述 投票:0回答:1

我有一个基于 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);
        });
}
node.js axios gmail gmail-api
1个回答
0
投票

您的问题似乎与写入文件时如何处理 PDF 内容有关。您可以尝试使用二进制编码保存文件,并将 responseType 用作 'stream',而不是直接使用 'base64' 编码,以获得更直接的方法。这是您的函数的更新版本:

const fs = require('fs');
const axios = require('axios');

function downloadAttachment(attachmentId, filename, messageId, callback) {
    axios.get(`https://gmail.googleapis.com/gmail/v1/users/me/messages/${messageId}/attachments/${attachmentId}`, {
        responseType: 'stream', // Use 'stream' instead of 'arraybuffer'
        headers: {
            Authorization: `Bearer ${token.access_token}`,
        },
    })
        .then(response => {
            const writeStream = fs.createWriteStream(filename);
            response.data.pipe(writeStream);

            writeStream.on('finish', () => {
                console.log(`Attachment saved locally: ${filename}`);
                callback();
            });

            writeStream.on('error', error => {
                console.error('Error writing attachment to file:', error);
            });
        })
        .catch(error => {
            console.error('Error downloading attachment:', error);
        });
}

// Example usage
const token = {
    access_token: 'your_access_token',
};

downloadAttachment('your_attachment_id', 'output.pdf', 'your_message_id', () => {
    console.log('Download complete.');
});

在此更新版本中,响应直接通过管道传输到由 fs.createWriteStream 创建的可写流中,这简化了保存文件的过程。这应该有助于避免不必要的内容转换,并确保文件保存为正确的 PDF。

© www.soinside.com 2019 - 2024. All rights reserved.