How to download a csv file requested through jquery/ajax from flask server [duplicate]

岁酱吖の 提交于 2021-01-29 07:30:44

问题


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:


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



来源:https://stackoverflow.com/questions/53740891/how-to-download-a-csv-file-requested-through-jquery-ajax-from-flask-server

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!