1

I am building a python flask web app. I am trying to get a CSV file downloaded through jquery/ ajax call.

This is how my ajax request looks like:

$(".download-btn").on("click", function(){
    $.ajax({
        type: 'GET',
        url: '/downloadFile',
        contentType: 'csv',
        cache: false,
        processData: false,
        async: false,
        success: function(data) {
            console.log("coming");
        },
    });

and this is by server code looks like:

app = Flask(__name__)
path = os.getcwd()

@app.route('/downloadFile',methods = ['GET'])
def download():
    logger.info('Checking file to download..')
    logger.info(path)
    return send_file(path+"/Generated/modified_file.csv",
                        mimetype='text/csv',
                        attachment_filename='modified_file.csv',
                        as_attachment=True)

For your information, "modifed_file.csv" is present inside the path specified before the request is being made.

While running the code I can see

"Checking file to download.." and "coming" in output. But the file is not getting downloaded.

Also if I do

console.log(data);

I can see the content of the file.

I am stuck. Any help is appreciated.

1 Answers1

0

I think it's because the file's content is stored in the data variable (of the "success" callback of $.ajax), so it's just a js variable for the browser.

I think the best (cleanest maybe?) thing you can do is wrap your .download-btn in a <a> tag with your download url in href

<a href="/downloadFile" target="_blank">
    <button class="download-btn">Download</button>
</a>

This way "the browser itself" makes the GET request to /downloadFile (in a new tab because of the target="_blank" attribute), receives the stream and downloads the file (and closes tab once the download is started).

Trio
  • 78
  • 7