Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flask send_file as attachment not working

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?

like image 922
Felix Avatar asked Jan 13 '23 15:01

Felix


1 Answers

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.

like image 195
Paolo Casciello Avatar answered Jan 21 '23 12:01

Paolo Casciello