将PDF二进制数据编码为base64不能与NodeJS一起使用 [英] Encoding PDF binary data to base64 not working with NodeJS

查看:273
本文介绍了将PDF二进制数据编码为base64不能与NodeJS一起使用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图获取来自API的PDF流返回并将其解析为base64,以将其嵌入客户端,API请求的主体返回的内容如下:

I'm trying to get a PDF stream return that comes from a API and parse it to base64 to embbed it in the client side, the body of the API request is returning something like this:

    %PDF-1.5
%����
4 0 obj
<<
/Type/XObjcect
/Subtype/Image
/Width 799
/Height 70
/ColorSpace/DeviceGray
/BitsPerComponent 8
/Filter/FlateDecode
/Length 5181
>>
stream
x���=H#�������A�&�)���B���4iba�&O8H
.
.
. 
(The rest was omitted)

我正尝试通过以下方式解析为base64:

I'm trying to parse to base64 this way:

console.log(typeof body); // STRING
const encoded = new Buffer.from(body).toString('base64'); //PDF NOT WORKING

但是当我得到这个base64并将其嵌入html时,它说表示该文件不可删除,当我尝试将其另存为.PDF文件时,也会发生同样的事情。

But when I'm getting this base64 and embedding it on the html it says that the file can't be oppened, the same thing happens when I trying to save it as .PDF file.

当我尝试将相同的pdf解析为base64时,这次从下载的pdf中,嵌入到html中的base64代码可以正常工作。

When I try to parse to base64 the same pdf but this time from a downloaded pdf, the base64 code when embedded in the html works fine.

  fs.readFile('/home/user/downloaded.pdf', function (err, data) {
    if (err) throw err;

    console.log(typeof data); //OBJECT
    const pdf = data.toString('base64'); //PDF WORKS
  });

我正在使用 const request = require('request'); 发出请求。

推荐答案

发出请求时,应将选项编码设置为null以获取缓冲区而不是字符串

When you make your request you should set option encoding to null for getting Buffer instead of String.

request({
    method: 'GET',
    encoding: null,
    uri: 'http://youdomain.com/binary.data'
}, (err, resp, data)=>{
    console.log(typeof data) //should be an Object
    console.log(data.toString('base64'))
})

这篇关于将PDF二进制数据编码为base64不能与NodeJS一起使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆