简体   繁体   English

res.download() 下载窗口没有出现

[英]res.download() download window not showing up

I created a download button that downloads the file on click.我创建了一个下载按钮,点击下载文件。 The problem is when I click the download button, I'm able to see the content that I want to download by using Chrome inspect -> Network -> Response but it is not opening a window to save the file to my PC.问题是当我点击下载按钮时,我可以通过使用Chrome inspect -> Network -> Response来查看我想要下载的内容,但它没有打开一个窗口来将文件保存到我的 PC。 For example, I'm trying to download text.txt which contains multiple lines of MY FILE string.例如,我正在尝试下载包含多行MY FILE字符串的text.txt I'm able to see it on Response tab but how can I download the .txt file.我可以在“ Response选项卡上看到它,但如何下载.txt文件。 在此处输入图片说明

Relevant React Code:相关反应代码:

<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})
    })
  }

Relevant Backend Code:相关后端代码:

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.
  });

The idea is that I will feed fileName to backend and then download it with res.download(uploadFolder+fileName, fileName);这个想法是我将fileName给后端,然后使用res.download(uploadFolder+fileName, fileName);下载它res.download(uploadFolder+fileName, fileName); line.线。 I think im suppose to use window.open('/download') but that just opens the homepage on a new tab or maybe I am just placing it wrong.我想我想使用window.open('/download')但这只是在新选项卡上打开主页,或者我只是把它放错了。

Okay, I have managed to solve my issue.好的,我已经设法解决了我的问题。 three main modifications were made to make this code and idea work.进行了三个主要修改以使此代码和想法起作用。

  1. Changing the request from POST to GET .将请求从POST更改为GET Another StackOverflow thread also mentions this. 另一个 StackOverflow 线程也提到了这一点。

  2. Using axios() instead of fetch() .使用axios()而不是fetch()

  3. Creating Blob object from the res.download(filePath, fileName) response value.res.download(filePath, fileName)响应值创建Blob对象。


Anyone else having this problem with the React Code part should check this Github link. 任何其他在React Code部分遇到此问题的人都应该检查这个 Github 链接。

Final State of the React function posted in the question问题中发布的 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);
        })
  }

Final State of the backend code posted in the question问题中发布的后端代码的最终状态

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM