1

I have one tex file and three images and I want that the user can click a button and download all three of them. It would be ideal if the four files would be as one tar file. My download works as follows right now

@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

this works fine for the tex file, but how can I tar up files within the flask app and send the tar file instead?

EDIT: Ok thanks to the comment below I came up with this code

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()

but how can I now download that tar file with the browser?

carl
  • 4,216
  • 9
  • 55
  • 103

1 Answers1

1

You should use the send_from_directory method that Flask provides for this =) It is the perfect use case for what you're doing.

What you can do is something like this:

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)

That will handle all of the downloading bits for you in a clean way.

rdegges
  • 32,786
  • 20
  • 85
  • 109