防止浏览器打开 json 文件,而是在从 Flask 应用程序发送时下载

Prevent browsers from opening json files and instead download when sent from flask app

我在 Flask 应用程序中有一个 JSON 文件,我通过 send_from_directory() 或 send_file() 发送我都试过了。这会在单击按钮时触发,但浏览器会直接打开文件而不是获取下载对话框。我研究了一下,发现 Firefox 和 Chrome 有一个内置选项可以执行此操作,但是我希望它始终下载而不是打开,无论浏览器中的设置如何。

烧瓶代码

def download_file():
    filename = "requiredFields.json"

    return send_from_directory(app.config['MAIN_FOLDER'],filename,as_attachment=True)

HTML 那个叫

<a href="{{url_for('download_file',filename = file)}}"class="btn btn-primary" type="button">Download</a>

如果您将 mimetype 设置为 'application/octet-stream' 那么浏览器应该保存它。

send_file(..., mimetype='application/octet-stream')

send_from_directory(..., mimetype='application/octet-stream')

文档:send_file

另请参阅:Do I need Content-Type: application/octet-stream for file download?


编辑:

最小工作示例 - 您只需在 index()

中设置正确的文件名

如果您有文件 .json.txt、图像、.pdf 或其他都没有关系。它适用于所有类型的文件。

from flask import Flask, render_template_string, send_from_directory

app = Flask(__name__)
app.config['MAIN_FOLDER'] = '.'

@app.route('/')
def index():
    all_filenames = [
        'requiredFields.json',
        'input.txt',
        'image.jpg',
        'document.pdf',
    ]
    
    return render_template_string('''
{% for file in all_files %}
    <a href="{{ url_for('download_file', filename=file) }}">Download {{file}}</a><br/>
{% endfor %}''', all_files=all_filenames)

#@app.route('/download_file/<filename>')
@app.route('/download_file/<path:filename>')
def download_file(filename):
    return send_from_directory(app.config['MAIN_FOLDER'], filename, as_attachment=True, attachment_filename=filename, mimetype='application/octet-stream')
    
if __name__ == '__main__':    
    app.run() #debug=True