2015-09-10 48 views
0

我有存儲在GridFS中的文件。我想向用戶顯示一個文件列表,並允許他們下載它們。我有以下代碼將文件保存到服務器,但我不知道如何將文件提供給客戶端。我如何使用Flask的GridFS提供文件?使用Flask從GridFS列表並提供文件

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

回答

0

而不是保存從GridFS的服務器的文件系統中檢索到的文件,將它傳遞到客戶端響應。您無法一次發送多個文件,因此您必須刪除選擇多個文件的功能。您根本不需要表單,只需在url中傳遞該名稱並在模板中創建鏈接列表即可。

@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> 
0

以服務文件,客戶端,你可以準備一個類似的觀點:

@app.route('/client/serve/<file_id>/', methods=['GET', 'POST']) 
@login_required 
def serve_file(file_id): 
    from mongoengine.connection import get_db 
    from gridfs import GridFS, NoFile 
    from bson.objectid import ObjectId 
    from flask import make_response 

    db = get_db() 
    fs = GridFS(db) 
    try: 
     f = fs.get(ObjectId(file_id)) 
    except NoFile: 
     fs = GridFS(db, collection='images') # mongoengine stores images in a separate collection by default 
     try: 
      f = fs.get(ObjectId(file_id)) 
     except NoFile: 
      raise ValueError("File not found!") 

    response = make_response(f.read()) 
    response.mimetype = 'image/jpeg' 
    return response 
相關問題