我创建了一个小型概念验证来测试从 GMAIL API 检索 PDF 附件。我能够成功阅读电子邮件和附件。我能够从附件中提取数据,经过一些尝试和错误后,当我什至无法打开 PDF 时,我现在可以打开 PDF。但 PDF 被渲染为乱码。此外,我的收件箱中的原始 PDF 大小与以编程方式检索的 PDF 不同。 我觉得这和base64解码有关系。我用谷歌/SO搜索了这个,并尝试了一些技巧,但似乎没有任何效果。
在搜索 SO 时,建议使用
decodeBase64
函数中的技巧来使 PDF 工作。我已将其包含在下面的代码中,但它也不起作用。
这是成功提取 PDF 附件并将其写入本地文件系统的代码。但 PDF 附件大小与我收件箱中的附件大小不同,打开时出现乱码。有什么建议吗?
const Base64 = require('js-base64')
......
// Successfully pulls attachments
async function getAttachment(messageId, attachmentId, auth) {
const response = await google.gmail('v1').users.messages.attachments.get({
auth: auth,
userId: 'me',
messageId: messageId,
id: attachmentId
});
return response.data;
}
// Stack Overflow suggestion to fix PDF. It fixed "Unable to Open" file but PDF is still garbled.
function decodeBase64(str) {
str = str.replace(/_/g, '/').replace(/-/g, '+') // important line
return Base64.atob(str)
}
// Working code to pull messages with attachments from GMAIL code hidden for brevity
....
....
getAttachment(messageId, attachmentId, auth).then(attachmentBufferData => {
fs.writeFile(part.filename, decodeBase64(attachmentBufferData.data));
});
在你的展示脚本中,做如下修改怎么样?
function decodeBase64(str) {
str = str.replace(/_/g, '/').replace(/-/g, '+') // important line
return Base64.atob(str)
}
function decodeBase64(str) {
str = str.replace(/_/g, '/').replace(/-/g, '+');
return Buffer.from(str, "base64");
}
str = str.replace(/_/g, '/').replace(/-/g, '+');
。因此,请测试有和没有它的两种模式。另外,请修改如下。
getAttachment(messageId, attachmentId, auth).then(attachmentBufferData => {
fs.writeFile(part.filename, decodeBase64(attachmentBufferData.data));
});
getAttachment(messageId, attachmentId, auth).then((attachmentBufferData) => {
fs.writeFileSync(part.filename, decodeBase64(attachmentBufferData.data));
});