简体   繁体   English

将 base64 字符串数据转换为 PDF 文件以从 API 下载 - NodeJS

[英]Convert base64 string of data into PDF file for download from API - NodeJS

I have a nodeJS API configured which connects to another API and retrieves a data object, which is a Base64 string.我配置了一个 nodeJS API,它连接到另一个 API 并检索一个数据对象,它是一个 Base64 字符串。

The client that calls the API endpoint needs to download a PDF file that is made from the base64 data.调用 API 端点的客户端需要下载由 base64 数据制成的 PDF 文件。

How should the data be returned to the client so that it can be converted/prompt download from the browser?应该如何将数据返回给客户端,以便可以从浏览器转换/提示下载? Should this be done client or server-side?这应该在客户端还是服务器端完成?

Base64 is HTML safe and has utility when you want to create a data URL as a link. Base64 是 HTML 安全的,并且在您想要创建数据 URL 作为链接时具有实用程序。 This would allow to preload the PDF so that the user instantly gets the file when clicking the link.这将允许预加载 PDF,以便用户在单击链接时立即获取文件。

However, you just want to download it directly, so just convert it as binary on server side to reduce the network overhead related to base64, and keep the client as light as possible (load less data, use less resources).但是,您只是想直接下载它,因此只需在服务器端将其转换为二进制文件,以减少与base64相关的网络开销,并保持客户端尽可能轻巧(加载更少的数据,使用更少的资源)。

Just set the proper content-type in the response ( application/pdf if you want the PDF to be opened with the browser's PDF plugin, or application/octet-stream if you want to trigger a regular download) then just create a link to it with a classic <a href=... .只需在响应中设置正确的内容类型( application/pdf如果您希望使用浏览器的 PDF 插件打开 PDF,或者application/octet-stream如果您想触发常规下载)然后只需创建一个链接带有经典的<a href=... You can also do one of the following:您还可以执行以下操作之一:

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

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