17

我有一个页面显示目录中的文件列表。当用户单击“下载”按钮时,所有这些文件都被压缩成一个文件,然后提供下载。我知道如何在单击按钮时将此文件发送到浏览器,并且我知道如何重新加载当前页面(或重定向到不同的页面),但是是否可以在同一步骤中同时执行这两项操作?或者使用下载链接重定向到不同的页面是否更有意义?

我的下载是使用 Flask API 的send_from_directory. 相关测试代码:

@app.route('/download', methods=['GET','POST'])
def download():
    error=None
    # ...

    if request.method == 'POST':
        if download_list == None or len(download_list) < 1:
            error = 'No files to download'
        else:
            timestamp = dt.now().strftime('%Y%m%d:%H%M%S')
            zfname = 'reports-' + str(timestamp) + '.zip'
            zf = zipfile.ZipFile(downloaddir + zfname, 'a')
            for f in download_list:
                zf.write(downloaddir + f, f)
            zf.close()

            # TODO: remove zipped files, move zip to archive

            return send_from_directory(downloaddir, zfname, as_attachment=True)

    return render_template('download.html', error=error, download_list=download_list)

更新:作为一种解决方法,我现在通过单击按钮加载一个新页面,这允许用户send_from_directory在返回更新列表之前启动下载(使用 )。

4

1 回答 1

8

您是否在 nginx 或 apache 等前端 Web 服务器后面运行烧瓶应用程序(这将是处理文件下载的最佳方式)。如果您使用的是 nginx,则可以使用“X-Accel-Redirect”标头。对于这个示例,我将使用该目录/srv/static/reports作为您在其中创建 zip 文件并希望从中提供它们的目录。

nginx.conf

在该server部分

server {
  # add this to your current server config
  location /reports/ {
    internal;
    root /srv/static;
  }
}

你的烧瓶方法

将标头发送到 nginx 到服务器

from flask import make_response
@app.route('/download', methods=['GET','POST'])
def download():
    error=None
    # ..
    if request.method == 'POST':
      if download_list == None or len(download_list) < 1:
          error = 'No files to download'
          return render_template('download.html', error=error, download_list=download_list)
      else:
          timestamp = dt.now().strftime('%Y%m%d:%H%M%S')
          zfname = 'reports-' + str(timestamp) + '.zip'
          zf = zipfile.ZipFile(downloaddir + zfname, 'a')
          for f in download_list:
              zf.write(downloaddir + f, f)
          zf.close()

          # TODO: remove zipped files, move zip to archive

          # tell nginx to server the file and where to find it
          response = make_response()
          response.headers['Cache-Control'] = 'no-cache'
          response.headers['Content-Type'] = 'application/zip'
          response.headers['X-Accel-Redirect'] = '/reports/' + zf.filename
          return response

如果您使用的是 apache,您可以使用他们的 sendfile 指令http://httpd.apache.org/docs/2.0/mod/core.html#enablesendfile

于 2011-03-28T18:06:45.777 回答