【问题标题】:Download files from GridFS Stream NodeJS Backend / React Front End从 GridFS Stream NodeJS 后端/反应前端下载文件
【发布时间】:2019-03-10 07:08:40
【问题描述】:

我已经设置了一个提供 zip 文件的 GridFS 流,如果我在浏览器中输入 API url,则 zip 文件会下载到我的计算机上,这就是我想要发生的事情。但是,当我从前端 React 应用程序发出获取请求时,我得到一个数据对象并且没有下载效果。我已经能够使用 window.location.href 进行下载,但我已经在生产中对此进行了测试,它只是将我发送到该 localhost URL(在生产中不存在)。只是想对此有所了解,我的目标是用户可以单击下载按钮,然后将 zip 文件发送给用户并开始下载。谢谢!!

【问题讨论】:

    标签: node.js mongodb reactjs gridfs gridfs-stream


    【解决方案1】:

    如果有人遇到同样的问题,我决定回答我自己的问题。要从 GridFS 流下载文件,请在您的 axios 请求中包含 responseType: 'blob'。然后使用 FileSaver 等客户端文件库保存文件。

    还要确保在后端路由中包含适当的标头。

    client.js

    onDownloadSampleClick = () => {
        axios({
          method: "GET",
          url: "/api/test/stream/90b7d1d5ed550882284dcf6f62774963.zip",
          responseType: "blob"
        })
          .then(response => {
            this.setState({ fileDownloading: true }, () => {
              FileSaver.saveAs(response.data, "sparta_sample_pack.zip");
            });
          })
          .then(() => {
            this.setState({ fileDownloading: false });
            console.log("Completed");
          });
      };
    

    gridfs 路由

    router.get("/api/test/stream/:filename", (req, res) => {
      res.set({
        "Accept-Ranges": "bytes",
        "Content-Disposition": `attachment; filename=${req.params.filename}`,
        "Content-Type": "application/zip"
      });
      gfs.files.findOne({ filename: req.params.filename }, (err, file) => {
        if (!file || file.length === 0) {
          return res.status(404).json({
            error: "That File Doesn't Exist"
          });
        }
        if (file.contentType === "application/zip") {
          // Read output to browser
          const readstream = gfs.createReadStream(file.filename);
          readstream.pipe(res);
        } else {
          res.status(404).json({
            error: "This is not an zip file"
          });
        }
      });
    });
    

    【讨论】:

      【解决方案2】:

      您应该在服务器响应中设置标题Content-Disposition: attachment; filename="filename.jpg"

      【讨论】:

        猜你喜欢
        • 2021-10-02
        • 2020-12-18
        • 2017-11-10
        • 2021-08-31
        • 2020-07-18
        • 2021-11-26
        • 1970-01-01
        • 2021-06-27
        • 1970-01-01
        相关资源
        最近更新 更多