首页 > 解决方案 > 从服务器下载文件(Nodejs Express > React)

问题描述

我如何向用户发送文件(docx)?这是我的服务器代码:

  app.get('/api/topic/file/:id', function (req, res, next) {
    Topic.findByIdAndUpdate(req.params.id)
      .exec()
      .then((topic) => {
        let filepath = topic.news_file[0]
        console.log('filepath', filepath)
        res.download(filepath, topic.name + '.docx', function (err) {
          if (err) {
            console.log('api get file err ', err);
          } else {
            // decrement a download credit, etc.
          }
        });
      }).catch((err) => console.log('error', err));
  })

这不会触发浏览器上的下载。我正在使用反应作为前端。在客户端我有一个按钮在点击时触发它:

handleDownload() {
        if (this.state.lastClicked) {
          fetch("/api/topic/file/" + this.state.lastClicked._id)
            .then(results => {
              console.log('results', results)
              return results;
            })
        } else {
            //somthings...
        }
      }

标签: node.jsreactjsexpressdownload

解决方案


使用downloadjs找到了解决方案..

var download = require("downloadjs")
 async handleDownload() {
    const res = await fetch("/api/topic/file/" + this.state.lastClicked._id);
    const blob = res.blob();
    download(blob, this.state.lastClicked.name + '.docx');
  }

推荐阅读