5

I'm using flask's send_file method to try and make the browser download a .txt file. Problem is the browser does not download anything.

Here's my python function:

@app.route('/download_zip', methods=['POST'])
def download_zip():
    file_name = 'test.txt'
    return flask.send_file(file_name, as_attachment=True, mimetype='text/plain')

Here's my jQuery function that triggers the POST request:

function batchDownload() {
    $.post('/download_zip', {
        file_name: 'temp.zip'
    }).done(function(data) {
        alert(data);
    }).fail(function() {
        alert('Error.  Could not download files :(');
    });
}

Funny thing is the alert(data) in the .done(...) callback displays the file's content to the browser. So the browser is receiving the file content but just not downloading it.

Any ideas?

Thanks in advance!


EDIT

Added a form to the page:

<form id="download"></form>

And added this to the .done(...) callback:

    $form = $('#download');
    $form.submit();

I'm guessing I need to somehow link the data (file) returned by the server response to the POST request?

Felix
  • 3,783
  • 5
  • 34
  • 53

1 Answers1

10

This is not a flask related question. It's how browsers and javascript works.

You're downloading the file in Ajax so the result is passed to your Ajax callback.

You want instead to make the browser download data in his usual way.

To do so you must use a form and call the .submit() method on it. Just create the form in the page with hidden fields and submit it in the javascript function. It should do the trick.

Paolo Casciello
  • 7,982
  • 1
  • 43
  • 42
  • Thanks for the response! I see, yeah this is my website project, so plenty to learn :) I'll give this a go and get back to you. – Felix Aug 16 '13 at 22:48
  • Okay, I added the form and submit it from the javascript function (see edit). How do I link the file to the form? – Felix Aug 16 '13 at 23:21
  • 2
    @nissemand no. You need to use `
    ...
    ` and instead of using Ajax you just `.submit()` the form. This way the browser performs the `POST` directly and triggers your download.
    – Paolo Casciello Aug 17 '13 at 13:20