NodeJS Gmail附件下载问题:PDF内容转字符串求修复方案
修复Gmail附件PDF下载为字符串的问题
你的代码核心问题在于对Gmail API返回的附件数据格式处理错误,以及axios的responseType设置不当。以下是具体修复方案:
问题分析
Gmail API返回的附件数据是JSON格式,其中data字段是base64url编码的内容(而非直接的二进制数据)。你当前设置responseType: 'arraybuffer'会让axios把JSON响应当成二进制数据解析,后续再用Buffer.from(response.data, 'base64')解码自然会出错,导致生成的PDF文件内容异常。
修复步骤
- 移除
responseType: 'arraybuffer'配置,让axios默认返回JSON格式的响应。 - 将Gmail返回的base64url编码转换为标准base64(替换
-为+,_为/,并补全末尾的=)。 - 用正确的base64字符串生成Buffer并写入文件。
修正后的代码
function downloadAttachment(attachmentId, filename, messageId, callback) { axios.get(`https://gmail.googleapis.com/gmail/v1/users/me/messages/${messageId}/attachments/${attachmentId}`, { headers: { Authorization: `Bearer ${token.access_token}`, }, }) .then(response => { // 转换base64url为标准base64 const base64Data = response.data.data .replace(/-/g, '+') .replace(/_/g, '/') .padEnd(response.data.data.length + (4 - response.data.data.length % 4) % 4, '='); // 生成Buffer并写入文件 fs.writeFileSync(filename, Buffer.from(base64Data, 'base64')); console.log(`Attachment saved locally: ${filename}`); callback(); }) .catch(error => { console.error('Error downloading attachment:', error); }); }
额外说明
如果你的token可能过期,建议在请求前添加token有效性校验,避免因权限问题导致下载失败。另外,推荐使用异步的fs.writeFile代替同步的fs.writeFileSync,避免阻塞事件循环。
内容的提问来源于stack exchange,提问作者Sultan Ahmed Siddiqui
相关产品推荐
相关产品推荐

