Flask send_file how the application does not work

I use the flask send_file method to try to make the browser load the .txt file. The problem is that the browser is not loading anything.

Here is 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 is my jQuery function that runs 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 :('); }); } 

It's funny that alert(data) in the .done(...) displays the contents of the file in the browser. Thus, the browser receives the contents of the file, but simply does not download it.

Any ideas?

Thanks in advance!


EDIT

Added form to page:

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

And added this to the .done(...) return message:

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

I assume that I need to somehow connect the data (file) returned by the server response to the POST request?

+3
source share
1 answer

This is not a flask issue. This works both browsers and javascript.

You upload the file to Ajax, so the result is passed to your Ajax callback.

Instead, you want the browser to load data in the usual way.

To do this, you must use form and call the .submit() method. Just create a form on the page with hidden fields and send it to the javascript function. He has to do the trick.

+7
source

Source: https://habr.com/ru/post/1497344/


All Articles