Flask send_file作为附件不起作用 [英] Flask send_file as attachment not working

查看:95
本文介绍了Flask send_file作为附件不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用flask的 send_file 方法尝试使浏览器下载.txt文件.问题是浏览器无法下载任何内容.

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.

这是我的python函数:

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

这是触发POST请求的jQuery函数:

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 :(');
    });
}

有趣的是 .done(...)回调中的 alert(data),将文件的内容显示给浏览器.因此,浏览器正在接收文件内容,但未下载文件.

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.

有什么想法吗?

提前谢谢!

编辑

在页面上添加了一个表单:

Added a form to the page:

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

并将其添加到 .done(...)回调中:

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

我猜我需要以某种方式将服务器响应返回的数据(文件)链接到POST请求?

I'm guessing I need to somehow link the data (file) returned by the server response to the POST request?

推荐答案

这不是烧瓶相关的问题.这就是浏览器和javascript的工作方式.

This is not a flask related question. It's how browsers and javascript works.

您正在Ajax中下载文件,因此结果将传递到您的Ajax回调中.

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.

为此,您必须使用 form 并在其上调用 .submit()方法.只需在带有隐藏字段的页面中创建 form 并在javascript函数中提交即可.它应该可以解决问题.

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.

这篇关于Flask send_file作为附件不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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