【问题标题】:Download pdf file with Vue js in mevn stack在 mevn 堆栈中使用 Vue js 下载 pdf 文件
【发布时间】:2020-12-21 18:39:43
【问题描述】:

我的节点后端有以下方法生成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 文件?

【问题讨论】:

    标签: javascript node.js vue.js vuejs2 axios


    【解决方案1】:

    这以某种方式完成了工作,但仍在寻找 高效的方式。

    在服务器/app.js 中。添加发票目录的静态路径

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

    将文件名传递给前端。

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

    在 Order.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');
    }
    

    【讨论】:

      猜你喜欢
      • 2022-01-14
      • 1970-01-01
      • 1970-01-01
      • 2020-05-18
      • 2020-07-01
      • 2018-12-06
      • 2020-06-07
      • 1970-01-01
      • 2021-01-26
      相关资源
      最近更新 更多