Node js Converting pdf Buffer back to pdf

守給你的承諾、 提交于 2019-12-18 16:57:31

问题


I have created a pdf with the browser in Javascript and sent it via post to the server using this code:

var blob = pdf.output('blob')
var xhr = new XMLHttpRequest();
xhr.open('post','/upload', true);
xhr.setRequestHeader("Content-Type", "application/pdf");                                
xhr.send(blob);

I would like to save as pdf on the server running Node with express. I have come up with the following code using express and body-parser package:

const bodyParser = require('body-parser');

app.use(bodyParser.urlencoded({ limit: '1gb', extended: false }));
app.use(bodyParser.raw({ limit: '1gb', type: 'application/pdf' }));

app.post('/upload', function(req, res){
   console.log(req.body);      
}

req.body is a Buffer, Uint8Array[653120]:

I need help converting it back to pdf before saving in on the server. Any help would be appreciated. Thanks.


回答1:


A buffer is a literal binary representation. Just write it to a file directly without .toString() and it should be the file you want.

e.g. to try fs.writeFileSync('some.pdf', req.body)

I do not actually recommend using writeFileSync - instead use writeFile which is async and needs a callback, but won't block other http requests from being accepted.

A Buffer is just a sequence of bytes without any encoding. If you expect body to look like xml when you log it out, try .toString('utf8') on it. hex/utf8/base64 are just representations of binary. They're like a function to unpack, or pack data. In this case you want the sequence of bytes in your buffer to exist on disk as-they-are; so messing with the encoding is undesirable.



来源:https://stackoverflow.com/questions/49722745/node-js-converting-pdf-buffer-back-to-pdf

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!