2016-08-27 47 views
1

我有一个tex文件和三个图像,我希望用户可以点击一个按钮,并下载所有三个。如果这四个文件将作为一个tar文件,那将是理想的。我下载的作品作为现在tar文件和下载与烧瓶的应用程序

@app.route('/download_tex', methods=['GET', 'POST']) 
@login_required 
def download_tex(): 
    latext_text = render_template('get_lates.html') 

    filename = 'test' 
    response = make_response(latext_text) 
    response.headers["Content-Disposition"] = "attachment; filename=%s.tex" % filename 

    return response 

这工作正常的TEX文件遵循,但我怎么能焦油的文件烧瓶内的应用程序和发送tar文件呢?

编辑:好的感谢评论下面我想出了这个代码

latext_text = render_template('get_latex.html') 

latex_file = open(basedir + '/app/static/statistics/latex_%s.tex' % current_user.username, "w") 
latex_file.write(latext_text) 
latex_file.close() 

filename = 'tarfile_%s.tar.gz' % current_user.username 
filepath = basedir + '/app/static/statistics/%s' % filename 

tar = tarfile.open(filepath, "w:gz") 
tar.add(basedir + '/app/static/statistics/image1.png') 
tar.add(basedir + '/app/static/statistics/image2.png') 
tar.add(basedir + '/app/static/statistics/image3.png') 
tar.add(basedir + '/app/static/statistics/latex_%s.tex' % current_user.username) 
tar.close() 

,但我怎么能现在下载与浏览器tar文件?

+0

http://stackoverflow.com/a/17081026/1005215和https://gist.github.com/boris317/3693796 –

回答

1

您应该使用Flask为此提供的send_from_directory方法=)这是您正在做的事情的完美用例。

你可以做的是这样的:

from flask import send_from_directory 

# code here ... 

filename = 'tarfile_%s.tar.gz' % current_user.username 
filedir = basedir + '/app/static/statistics/' 

# tar code here ... 

return send_from_directory(filedir, filename, as_attachment=True) 

,将处理在清洁的方式为您的所有下载位。