res.download()下载窗口未显示

时间:2019-12-20 07:38:46

标签: javascript node.js reactjs express http

我创建了一个下载按钮,可以单击下载文件。问题是,当我单击下载按钮时,可以使用Chrome inspect -> Network -> Response看到要下载的内容,但没有打开将文件保存到PC的窗口。 例如,我正在尝试下载包含多行text.txt字符串的MY FILE。我可以在Response标签上看到它,但是如何下载.txt文件。enter image description here

相关的React代码:

<button onClick={(e) => downloadHandler(e)}>Download</button>
    let downloadHandler = (e) =>{
      const fileName = e.target.parentElement.id;
      fetch('http://localhost:3001/download',{
        method: 'post',
        headers: {'Content-Type': 'application/json'},
        body: JSON.stringify({id: fileName})
    })
  }

相关后端代码:

const uploadFolder = `${__dirname}` + `\\uploads\\`;
app.post('/download', function(req, res){
    let fileName = req.body.id; // example output: 'dog.jpg'
    res.download(uploadFolder+fileName, fileName); // Set disposition and send it.
  });

我的想法是我将fileName传送到后端,然后在res.download(uploadFolder+fileName, fileName);行中下载它。我认为应该使用window.open('/download'),但这只是在新标签页上打开主页,或者我只是将其放置在错误的位置。

1 个答案:

答案 0 :(得分:0)

好的,我已经设法解决了我的问题。为了使此代码和构想生效,进行了三个主要修改。

  1. 将请求从POST更改为GETAnother StackOverflow thread also mentions this.

  2. 使用axios()代替fetch()

  3. 根据Blob响应值创建res.download(filePath, fileName)对象。


Anyone else having this problem with the React Code part should check this Github link.

问题中发布的React函数的最终状态

    let downloadHandler = (e) =>{
      const fileName = e.target.parentElement.id;
    axios({
        method: 'get',
        url: 'http://localhost:3001/download/'+fileName,
        responseType: 'blob',
        headers: {},
        })
        .then((res) => {
            const url = window.URL.createObjectURL(new Blob([res.data]));
            const link = document.createElement('a');
            link.href = url;
            link.setAttribute('download', fileName);
            document.body.appendChild(link);
            link.click();
        })
        .catch((error) => {
            alert(error);
        })
  }

问题中发布的后端代码的最终状态

const uploadFolder = `${__dirname}` + `\\uploads\\`;
app.get('/download/:filename', function(req, res){
    let fileName = req.params.filename
    const filePath = uploadFolder+fileName;
    res.download(filePath, fileName);
  });