使用Flask列出并提供GridFS中的文件 [英] List and serve files from GridFS with Flask

查看:65
本文介绍了使用Flask列出并提供GridFS中的文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的文件存储在GridFS中.我想向用户显示文件列表,并允许他们下载文件.我有以下代码将文件保存到服务器,但不确定如何将文件提供给客户端.如何使用Flask从GridFS提供文件?

I have files stored in GridFS. I want to show the user a list of files, and allow them to download them. I have the following code that saves the file to the server, but I'm not sure how to serve the file to the client. How do I serve files from GridFS with Flask?

<form id="submitIt" action="/GetFile" method="Post">
{% for file in List %}
<input type="checkbox" name="FileName" value={{file.strip('u').strip("'")}}>{{file.strip('u').strip("'")}}<br>
{% endfor %}
<a href="#" onclick="document.getElementById('submitIt').submit();">Download</a>
</form>

@app.route('/GetFile',methods=['POST'])
def GetFile():
    connection = MongoClient()
    db=connection.CINEfs_example
    fs = gridfs.GridFS(db)
    if request.method == 'POST': 
        FileName=request.form.getlist('FileName')
        for filename in FileName:
            EachFile=fs.get_last_version(filename).read()
            with open(filename,'wb') as file2:
                file2.write(EachFile)
    return 'files downloaded'

推荐答案

作为响应,与其将从GridFS检索到的文件保存到服务器的文件系统中,不如将其传递给客户端.您不能一次发送多个文件,因此必须删除选择多个文件的功能.您根本不需要表单,只需在url中传递名称并在模板中创建链接列表即可.

Rather than saving the file retrieved from GridFS to the server's filesystem, pass it on to the client in response. You cannot send more than one file at once, so you'll have to remove the ability to select multiple files. You don't need a form at all, just pass the name in the url and create a list of links in the template.

@app.route('/get-file/<name>')
@app.route('/get-file')
def get_file(name=None):
    fs = gridfs.GridFS(MongoClient().CINEfs_example)

    if name is not None:
        f = fs.get_last_version(name)
        r = app.response_class(f, direct_passthrough=True, mimetype='application/octet-stream')
        r.headers.set('Content-Disposition', 'attachment', filename=name)
        return r

    return render_template('get_file.html', names=fs.list())

get_file.html :

<ul>{% for name in names %}
<li><a href="{{ url_for('get_file', name=name) }}">{{ name }}</a></li>
{% endfor %}</ul>

这篇关于使用Flask列出并提供GridFS中的文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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