0

Express的版本是4.16.4

我想从以下位置下载NodeJs

list.on("click", "a[data-facture]", function () {
            var facture = $(this).data("facture");
            $.ajax({
                url: "/track/vehicule/downloadfacturemaintenance",
                data: { "facture": facture },
                type: "POST",
                success: function (data, status, xhr) {},
                error: function (xhr, status, error) {}
            });
        });

router.post("/downloadfacturemaintenance", function (req, res) {
    var facture = req.body.facture;
    var fichier = facture.substring(facture.lastIndexOf("/") + 1);
    var ext = fichier.substring(fichier.lastIndexOf("."));
    fichier = fichier.substring(0, fichier.indexOf("_"));
    res.download(facture, fichier.concat(ext));
});

在运行时,当我单击链接然后没有下载开始!那么我的代码有什么问题?

4

1 回答 1

1

您正在使用$.ajax它,然后它无法像您单击链接那样启动下载过程。

Blob但是你可以用对象来伪造这个动作。

list.on("click", "a[data-facture]", function () {
  var facture = $(this).data("facture");
  $.ajax({
    url: "/track/vehicule/downloadfacturemaintenance",
    data: { "facture": facture },
    type: "POST",
    success: function (data, status, xhr) {
      // data => Blob
      const blob = new Blob([data]);

      // the file name from server.
      const fileName = xhr.getResponseHeader('fileName') || 'data.txt';

      var url = window.URL.createObjectURL(blob);
      const a = document.createElement('a');
      a.style.display = 'none';
      a.href = url;
      a.download = fileName;
      document.body.appendChild(a);
      a.click();
      window.URL.revokeObjectURL(url);
    },
    error: function (xhr, status, error) { }
  });
});
于 2020-01-30T08:57:25.523 回答