【问题标题】:Download an excel file saved on flask server下载保存在烧瓶服务器上的 excel 文件
【发布时间】:2020-09-20 10:26:49
【问题描述】:

我有一个烧瓶应用程序,在下载文件夹中有一个现有的 xlsx 文件。我正在尝试通过单击按钮让前端下载 excel 文件。截至目前,我的烧瓶服务器正在正确访问该文件,但在响应中将其作为无意义的字符串数据发送。我假设我需要使用一些库将数据解析为 Excel 工作簿,然后下载它,但我无法找到答案。 这是烧瓶代码:


    @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】:

您的服务器似乎已经在发送 blob。所以在前端,做:

  • 使用URL.createObjectURL并从response.data创建url对象
  • 动态创建锚标记并将 url 对象关联到href
  • 调用click(),它将在客户端下载文件
  • 移除锚标记

代码 sn-p

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-08-25
    • 1970-01-01
    • 1970-01-01
    • 2022-01-25
    • 1970-01-01
    • 2019-01-01
    • 1970-01-01
    • 2021-08-03
    相关资源
    最近更新 更多