【问题标题】:I've got an issue with ReactJS to download a file from Nodejs我在使用 ReactJS 从 Nodejs 下载文件时遇到问题
【发布时间】:2020-12-19 15:45:40
【问题描述】:

我需要一些帮助来解决一个问题。我尝试从服务器 Nodejs 下载客户端 ReactJs 上的文件。 我已经进入了我的 server.js :

router.route("/download/:filesaveas").get(function(req, res) {
  const fileLocation = "public/files/" + req.params.filesaveas;
  const file = req.params.filesaveas;
  res.download(fileLocation, file, (err) => {
    if (err) console.log(err);
});

当我尝试直接从服务器 http://localhost:4000/cww/download/testfile.pdf 下载时,下载正常,我没有任何错误并且文件没有损坏。

在我的客户端,我有一个函数 downloadFile,它由按钮“onclick”操作调用。

import download from 'downloadjs'

downloadFile = (filetodownload) => {
        axios.get('http://localhost:4000/cww/download/'+filetodownload)
        .then(res => {
            var filename = "testfile.pdf"
            download(res.data, scriptname, "text/plain");
        });
     }

当我点击按钮时。下载了一些东西,但文件似乎已损坏。无法打开...我想,服务器的响应数据有问题。 通过执行 console.log(res.data),我可以看到我的内容 PDF 的一部分,但有些奇怪 字符(如编码),但无法下载正确的文件。

感谢您的帮助。

【问题讨论】:

    标签: node.js reactjs download mern


    【解决方案1】:

    如果您想要最简单的选择,那就是使用该文件的地址打开一个新选项卡,该地址仅在路由公开时才有效。

    const newTab = false;
    window.open('http://localhost:4000/cww/download/testfile.pdf',newTab ? '' : '_self' );
    

    但是你可以在不接触文件编码的情况下做到这一点,甚至可以使用 axios:

      onClick() {
        const fileName = 'testfile.pdf';
        fetch('http://localhost:4000/cww/download/testfile.pdf', {
          method: 'GET',
          headers: {
           'Content-Type': 'application/json'
           // Security Headers if needed
          },
          body: undefined,
        })
          .then((data) => {
            return data.blob();
          })
          .then((data) => {
            if (data.size === 0) {
              throw new Error('File not found');
            }
            const fileURL = URL.createObjectURL(data);
            const downloadLink = document.createElement('a');
            downloadLink.href = fileURL;
            downloadLink.download = fileName;
            downloadLink.click();
          })
          .catch((err) => {
            console.log(err);
            //  Error Action
          });
      }
    

    后端只会将文件流式传输给用户。

    我对 res.download 了解不多(可能是更好的解决方案)

    import * as fs from 'fs';
    
    export async function getFile(request, response) {
    
      const fileStream = fs.createReadStream('yourFileAddress', {});
    
    
      fileStream.on('error', (err) => {
        console.log(err.message);
        response.status(404).send();
        fileStream.removeAllListeners();
      });
    
      fileStream.on('end', () => {
        console.log('Streamed successfully to user');
        fileStream.removeAllListeners();
      });
    
      // finally starting the stream
      fileStream.pipe(response);
    
    }
    
    

    【讨论】:

      【解决方案2】:

      感谢您的帮助!我刚刚发现我的错误! 我忘了添加 ReponseType: blob,现在它可以完美运行了 ;-)

      downloadFile = (filetodownload) => {
              axios.get('http://localhost:4000/cww/download/'+filetodownload, {responseType: 'blob'})
              .then(res => {
                  var filename = "testfile.pdf"
                  download(res.data, scriptname, "text/plain");
              });
           }
      

      【讨论】:

        猜你喜欢
        • 2015-11-27
        • 2012-10-22
        • 1970-01-01
        • 1970-01-01
        • 2020-03-06
        • 2015-02-24
        • 1970-01-01
        • 1970-01-01
        • 2017-01-14
        相关资源
        最近更新 更多