【问题标题】:Download zip file from nodejs with vuejs使用 vuejs 从 nodejs 下载 zip 文件
【发布时间】:2020-11-08 14:51:12
【问题描述】:

我正在尝试使用 vuejs 从 nodejs 下载一个 zip 文件。

我的问题是对话框出现时文件名周围有一个奇怪的下划线。

如果我手动设置:

const fileName="xmlFile.zip";

我没问题。

我附上了问题的图片。

这是从节点返回的标头:

Accept-Ranges: bytes
Access-Control-Allow-Origin: *
Access-Control-Expose-Headers: Content-Disposition
Cache-Control: public, max-age=0
Connection: keep-alive
Content-Disposition: attachment; filename="xmlFile.zip"
Content-Length: 164
Content-Type: application/zip
Date: Sun, 19 Jul 2020 13:55:15 GMT
ETag: W/"a4-17367574de4"
Last-Modified: Sun, 19 Jul 2020 13:50:41 GMT
X-Powered-By: Express

我做错了什么?

 //vuejs front end
        let response = await axios.post('/generateLoteXMLZIPConsulta');;
        let blob = await new Blob([response.data], {
          type: "application/zip",
        });
        const link = document.createElement("a");
        link.style.display = "none";
        link.href = window.URL.createObjectURL(blob);
        const fileName = response.headers["content-disposition"].match(
          /filename=(.*)/
        )[1];
        link.download = fileName;
        link.click();
        window.URL.revokeObjectURL(link.href);

 //backend nodejs
 router.post("/generateLoteXMLZIPConsulta", async (req, res) => {
    ....
    ....
    res.download(
            path.resolve(__dirname, "../../file.zip"),
            "xmlFile.zip"
    );
})      

【问题讨论】:

  • 能否请您发布您从节点获得的 HTTP 请求的响应?应该有这样的标题:"Content-Disposition": "attachment;filename=your-file-name.zip"。这样我们就可以弄清楚问题出在哪一边——节点还是 vue。
  • @Alex 我编辑了我的问题并添加了来自 nodejs 的标题。
  • 我发现了问题。我不知道为什么,但是 fileName 有一个额外的双引号。

标签: javascript node.js vue.js


【解决方案1】:

在查看您的其他详细信息后,我认为添加下划线是因为您的正则表达式,它似乎也捕获了双引号。

根据您的详细信息,响应头内容为:

Content-Disposition: attachment; filename="xmlFile.zip"

然后你像这样提取它:

const fileName = response.headers["content-disposition"].match(
          /filename=(.*)/
        )[1];

尝试登录控制台fileName。我认为这需要去掉双引号。

【讨论】:

  • 非常感谢。你确定。
  • 确保在节点中允许内容处置response.setHeader("Access-Control-Expose-Headers", "Content-Disposition")
猜你喜欢
  • 2020-12-04
  • 2018-03-20
  • 2015-08-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-07-19
  • 1970-01-01
  • 2017-10-22
相关资源
最近更新 更多