下载保存在flask服务器上的excel文件。

问题描述 投票:0回答:1

我有一个flask应用,在downloads文件夹里有一个现有的xlsx文件。我试图让前端在点击按钮时下载excel文件。目前,我的flask服务器正确地访问了该文件,但在响应中却将其作为无意义的字符串数据发送。我假设我需要使用一些库将数据解析成excel工作簿,然后下载,但我很难找到答案。下面是flask的代码。


    @app.route('/download')
    @handle_errors
    def downloadFile():
        filename = request.args.get('filename')
        uploadPath = sys.path[0] + '\\workflow\\downloads'
        return send_file(uploadPath + '\\' + filename, as_attachment=True)

这是前端的反应代码


    getFile = (e) => {
        e.preventDefault();
        e.persist();
        const filename = e.target.getAttribute('name');
        axios
          .get(`http://localhost:5000/download?filename=${filename}`)
          .then((data) => {
            console.log('this is data: ', data);
            console.log('Completed: download');
          })
          .catch(() => {
            console.log('We were not able to complete your request.');
          });
      };

excel reactjs flask download
1个回答
0
投票

你的服务器似乎已经发送了一个blob。所以在前端,做。

  • 使用 URL.createObjectURL 并从response.data中创建url对象
  • 在飞行过程中创建一个锚标签,并将url对象关联至 href
  • 召唤 click() 这将在客户端下载文件
  • 撕掉标签

代码片段

getFile = (e) => {
    e.preventDefault();
    e.persist();
    const filename = e.target.getAttribute('name');
    axios
      .get(`http://localhost:5000/download?filename=${filename}`)
      .then((data) => {
        console.log('this is data: ', data.data);
        const link = document.createElement('a');
        const url = URL.createObjectURL(data.data) //<---- this should be data.data
        link.download = true;
        link.href = url;
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
      })
      .catch(() => {
        console.log('We were not able to complete your request.');
      });
  };
© www.soinside.com 2019 - 2024. All rights reserved.