首页 > 解决方案 > 如何在javascript中将文件从base64重建为pdf?

问题描述

在 Nodejs 中,我收到了来自 api 的响应

{
  "file": "PHN0eWxlPnRlRrU3VRbUNDJyAvPjwvcD4K",
  "mime_type": "text/html",
  "document_type": "shippingLabel"
}

要重建文件,需要对来自节点的数据进行 base64 解码,并根据 mime_type 进行解释。

帮助我获取文件.pdf 并保存到目录。

标签: javascriptnode.js

解决方案


使用fs.writeFileSync(file, data[, options])

const fs = require('fs');

// get your response somehow...
const response = {
  file: 'PHN0eWxlPnRlRrU3VRbUNDJyAvPjwvcD4K',
  mime_type: 'text/html',
  document_type: 'shippingLabel'
};
// LUT for MIME type to extension
const ext = {
  'text/html': 'html',
  // ...
}

// save to shippingLabel.html
fs.writeFileSync(`${response.document_type}.${ext[response.mime_type]}`, response.file, 'base64');

推荐阅读