首页 > 解决方案 > 解码 Base64 pdf 给出损坏的文件

问题描述

有人可以解释为什么解码 Base64 会给出损坏的 pdf 吗?我需要找到如何解码 Base64 并获取 pdf 的方法。当我使用这项服务时

https://emn178.github.io/online-tools/base64_decode_file.html

我能够通过 Base64 并毫无问题地获取文件。

但是当我在 node.js 中做同样的事情时,我总是得到空(损坏的)文件。我尝试了不同的软件包,例如:js-base64、atob

他们都没有工作,得到与结果相同的空文件。

链接到我的代码: https ://repl.it/@afiliptsov/FaroffGloriousFormula

标签: node.jsbase64decoding

解决方案


您会收到损坏的 PDF,因为:

  1. 根据官方文档,该 Base64.decode()函数将 Base64 值解码为 UTF-8 字符串。如您所见,这是错误的函数,因为您需要将值解码为二进制数据。
  2. Base64.atob()函数完全符合您的需要,但是在保存数据时会出错,因为根据 官方文档,默认情况下,该fs.writeFile() 函数将数据保存为 UTF-8,而您要保存二进制数据。

要正确解码 Base64 值并将其存储为二进制数据,根据您的需要,您可以选择以下方法之一:

需要('js-base64').Base64.atob()

Base64.atob()保存文件时使用并指定二进制编码解码 Base64 值。这仅在您需要处理二进制数据时才有用。与其他方法不同,您必须安装和加载“js-base64”模块。

var bin = Base64.atob(stringToDecode);
// Your code to handle binary data
fs.writeFile('result_binary.pdf', bin, 'binary', error => {
    if (error) {
        throw error;
    } else {
        console.log('binary saved!');
    }
});

缓冲区.from

使用将 Base64 值转换为缓冲区Buffer.from()并将其保存到文件中而不指定编码。这仅在您需要处理缓冲区时才有用。

var buf = Buffer.from(stringToDecode, 'base64');
// Your code to handle buffer
fs.writeFile('result_buffer.pdf', buf, error => {
    if (error) {
        throw error;
    } else {
        console.log('buffer saved!');
    }
});

编码选项_

如果您不需要读取/修改二进制数据或缓冲区,只需在保存文件时指定编码选项。这种方法是最简单的一种,可能是最快和最节省内存的。

fs.writeFile('result_base64.pdf', stringToDecode, 'base64', error => {
    if (error) {
        throw error;
    } else {
        console.log('base64 saved!');
    }
});

推荐阅读