我正在 Node.js 上构建一个 API,它接收一些参数,服务器会生成一个包含所述参数的 PDF 文件,我希望 浏览器打开生成的文件。
文件已成功生成,但我不知道如何在浏览器上打开作为 ReadableStream 对象接收的文件。
这是我第一次使用 ReadableStream,所以我不知道处理这个问题的最佳方法是什么。
我的
app.js
const express = require('express');
const fs = require('fs');
const app = express()
app.use(express.json())
const port = process.env.PORT || 8080;
app.listen(port, () => console.log(`Listening on port ${port}...`));
//import the function to generate the PDF file
const pdf = require('./pdf');
app.post("/pdf", async (req, res) => {
const parameterData = req.body
await pdf(parameterData);
//We create the ReadableStream from the generated file
var data = fs.createReadStream('./test/output.pdf');
var stat = fs.statSync('./test/output.pdf');
res.setHeader('Content-Length', stat.size);
res.setHeader('Content-Type', 'application/pdf');
res.setHeader('Content-Disposition', 'attachment; filename=output.pdf');
data.pipe(res);
})
app.get("/", (req, res) => {
res.sendFile(__dirname + '/index.html');
})
我的
index.html
文件
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>POST DEMO</title>
</head>
<body>
<button>PDF</button>
</body>
<script>
const paramData = {
//object that contains the parameters
}
document.querySelector('button')
.addEventListener('click', (e) => {
fetch('/pdf', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(paramData)
})
.then((res) => {
console.log(res.body)
//This is where I would want to create the logic to open the file on the browser
})
});
</script>
打开 DevTools 并检查响应时,我可以在浏览器上确认“网络”选项卡上收到了 ReadableStream 对象
您可以使用 Blob - 这应该会得到您想要的结果。
.then((res) => {
return res.blob();
})
.then((blob) => {
const blobData = URL.createObjectURL(blob);
window.open(blobData, '_blank');
})