简体   繁体   English

检查base64字符串是否包含有效的PDF-仅此而已

[英]Check if base64 string contains a valid PDF - and nothing else

In my web application, users may only upload images and PDFs. 在我的Web应用程序中,用户只能上传图像和PDF。 These come as base64 strings from the front to the backend. 这些是从前端到后端的base64字符串。 There, on the Node.js 8.9 server, I want to do some sanity checking, ie test whether the base64 strings I get are actually just images and PDFs - and nothing else. 在那里,在Node.js 8.9服务器上,我想进行一些检查,即测试我得到的base64字符串是否实际上只是图像和PDF,而没有其他内容。

For images, that was easy. 对于图像,这很容易。 Using the sharp npm-module with failOnError true, gave me exactly what I wanted: One wrong char in the base64 string would cause a failure and the input would be rejected. 使用带有failOnError true的尖锐npm-module时,确实可以得到我想要的结果:base64字符串中的一个错误char会导致失败,并且输入将被拒绝。

However, for PDFs I cannot find a similar solution. 但是,对于PDF,我找不到类似的解决方案。 I've tried pdf2json (which seemed overpowered for my requirement anyway), but failed at passing base64 strings via converting to a buffer. 我尝试了pdf2json(无论如何我的需求似乎都过分了),但是在通过转换为缓冲区传递base64字符串时失败了。

I finally found an NPM module that does exactly what I expect: hummusJS. 我终于找到了一个N​​PM模块,它完全符合我的期望:hummusJS。 The code below works as far as my tests go: Valid PDFs are accepted, while invalid strings are rejected. 就我的测试而言,以下代码有效:接受有效的PDF,而拒绝无效的字符串。 Didn't notice any performance impacts so far. 到目前为止,没有发现任何性能影响。

var hummus = require('hummus');

let pdfBase64String = '<<base64 string here>>';
let bufferPdf;
try {
  bufferPdf = Buffer.from(pdfBase64String, 'base64');
  const pdfReader = hummus.createReader(new hummus.PDFRStreamForBuffer(bufferPdf));
  var pages = pdfReader.getPagesCount();
  if(pages > 0) {
      console.log("Parsable with Hummus and more than 0 pages. Seems to be a valid PDF!");
  }
  else {
      console.log("Unexpected outcome for number o pages: '" + pages + "'");
  }
}
catch(err) {
   console.log("ERROR while handling buffer of pdfBase64 and/or trying to parse PDF: " + err);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM