如何在快速路由响应中发送 PDF 并强制浏览器下载?
在本文中,我们将看到如何在快速路由的响应中发送 PDF 文件并让浏览器强制下载文件。
方法:
- 加载所需的包,然后创建一个快速应用程序。
- 定义主页和 PDF 下载请求的路由。
- 使用单个按钮创建index.html文件以下载 PDF。
- 单击按钮执行 ajax 调用以获取 PDF。
- 在xhrFields中将 ajax 调用的responseType指定为“blob”,因为“blob”用于存储图像、音频和视频等对象,因为它们比其他数据类型需要更多空间。
- 成功调用 ajax 后,将接收到的 PDF 文件从 blob 格式转换为 PDF 格式。
- 现在,让浏览器强制下载 PDF –
一种。创建一个隐藏的标签。
湾。使用 window.URL.createObjectURL() 方法创建对文件的引用。
C。将其href属性设置为 blob 的 URL。
d。将其下载属性设置为文件名。
e.单击标记。
F。从 DOM 中删除 标记。
G。释放现有对象 URL(对文件的引用),并让浏览器知道不再保留对文件的引用。
第 1 步:安装必要的软件包
首先,安装以下节点包。
npm install --save express
第 2 步:创建基本的 Express 服务器设置
创建一个名为app.js的文件,并使用以下代码,如下所示。
App.js
// Load necessary packages
const express = require("express");
// create an express app
const app = express();
// define PORT number to listen to the requests
const PORT = process.env.PORT || 3000;
// to serve files from uploads directory
app.use("/uploads", express.static("uploads"));
// express routes
app.use("/", require("./routes"));
// listen to requests
app.listen(PORT, () => console.log(`Server started running on PORT ${PORT}`));
routes.js
// Load necessary packages
const express = require("express");
// express router
const router = express.Router();
// respond with index.html when a GET request is made to the homepage
router.get("/", (req, res) => {
res.sendFile(__dirname + "/views/index.html");
});
// route for handling PDF request
router.get("/downloadPDF", (req, res) => {
res.download("uploads/Resume.pdf");
});
// export router middleware and use it in app.js
module.exports = router;
index.html
第 3 步:为应用定义路由
创建一个名为routes.js的文件,并使用以下代码,如下所示。
路由.js
// Load necessary packages
const express = require("express");
// express router
const router = express.Router();
// respond with index.html when a GET request is made to the homepage
router.get("/", (req, res) => {
res.sendFile(__dirname + "/views/index.html");
});
// route for handling PDF request
router.get("/downloadPDF", (req, res) => {
res.download("uploads/Resume.pdf");
});
// export router middleware and use it in app.js
module.exports = router;
第四步:运行服务器
现在使用以下命令启动您的快速服务器:
node app.js
第五步:打开浏览器,输入网址
打开您喜欢的浏览器并在地址栏中输入http://localhost:3000/downloadPDF然后按 Enter,Resume.pdf 文件将自动下载。
输出:
第 6 步:通过按钮使 PDF 可下载。
您可以使用按钮上的单击事件侦听器使浏览器单击按钮下载 PDF,然后向上述 URL 发出 ajax 请求。
要在单击按钮时下载 PDF,首先创建一个index.html文件,其内容如下:
索引.html
输出: