使用mevn堆栈中的Vue js下载pdf文件



我在节点后端有以下方法,该方法生成pdf并保存在服务器目录data/invoices/中。

exports.generateInvoice = async(req, res, next) => {
const orderId = req.params.orderId;
try {
const order = await  Order.findById(orderId);
const data = await order.populate("user.userId").execPopulate();
if (!order){
const error = new Error("Order not found");
error.statusCode = 404;
throw  error;
}
if (data.user.userId._id.toString() !== req.userId.toString()) {
return next(new Error("Unauthorized"));
}
const invoiceName = "invoice-" + orderId + ".pdf";
const invoicePath = path.join("data", "invoices", invoiceName);
let doc = new PDFDocument({ size: "A4", margin: 50 });
generateHeader(doc);
generateCustomerInformation(doc, data);
generateInvoiceTable(doc, data);
generateFooter(doc);
doc.end();
doc.pipe(fs.createWriteStream(invoicePath));
res.status(200).json({path: 'http://localhost:8080/'+invoicePath});
}catch (e){
if (!e.statusCode) {
e.statusCode = 500;
next(e);
}
}
}

generateHeader(doc);
generateCustomerInformation(doc, data);
generateInvoiceTable(doc, data);
generateFooter(doc);

只是我创建的辅助方法。

这是我的前端vue方法,它触发上面的方法来生成发票pdf。

methods: {
async getInvoice(orderId){
console.log("click");
const res = await this.$axios.get('product/get-invoice/'+ orderId, {
headers: {
Authorization: 'Bearer ' + this.userData.userToken
}
});
console.log(res);
}
},

如何下载最近创建的pdf?

这以某种方式完成了任务,但仍然看起来有效的方式。

在server/app.js.添加了发票目录的静态路径

app.use("/invoice", express.static(path.join(__dirname, "data/invoices")));

将文件名传递给前端。

exports.generateInvoice = async(req, res, next) => {
...........
res.json({
path: invoiceName
});
}

订单中.vue

async getInvoice(orderId) {
console.log("click");
const res = await this.$axios.get('product/get-invoice/' + orderId, {
headers: {
Authorization: 'Bearer ' + this.userData.userToken
}
});
window.open('http://localhost:8080/invoice/' + res.data.path, '_blank');
}

最新更新