如何从Flask服务器下载通过jquery/ajax请求的csv文件 [英] How to download a csv file requested through jquery/ajax from flask server

查看:96
本文介绍了如何从Flask服务器下载通过jquery/ajax请求的csv文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在构建python flask Web应用程序.我正在尝试通过jquery/ajax调用下载CSV文件.

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

这是我的ajax请求的样子:

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)

供您参考,在发出请求之前,指定的路径内包含"modifed_file.csv".

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.

如果我也这样做

console.log(data);

我可以看到文件的内容.

I can see the content of the file.

我被困住了.感谢您的帮助.

I am stuck. Any help is appreciated.

推荐答案

我认为这是因为文件的内容存储在 data 变量($ .ajax的成功"回调的)中,所以这只是浏览器的js变量.

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.

我认为您可以做的最好的(也许是最干净的?)方法是将您的 .download-btn 包装在< a> 标记中,并在href中添加下载网址

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>

通过这种方式,浏览器本身"向/downloadFile 发出GET请求(由于 target ="_ blank" 属性而在新选项卡中)接收流并下载文件(下载开始后关闭标签).

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

这篇关于如何从Flask服务器下载通过jquery/ajax请求的csv文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆