2016-10-21 13 views
0

Flaskを使用してMongoDbとの間でファイルをアップロードおよびダウンロードするWebアプリケーションを構築しています。まず、特定のコレクションのMongoDbデータベースで一致する文字列を検索し、一致する文字列があれば、ObjectIdを使用してダウンロードする動的URL(検索ページからクリック可能)を作成する必要があります。動的URLをクリックすると、特定のObjectIdのMongoDbに格納されているファイルを取得してダウンロードする必要があります。 response.headers['Content-Type']response.headers["Content-Dispostion"]を元の値に変更しようとしましたが、何らかの理由でダウンロードが正常に動作しません。Flaskを使用してMongoDBからファイルをダウンロードする

route.py

@app.route('/download/<fileId>', methods = ['GET', 'POST']) 
def download(fileId): 
    connection = pymongo.MongoClient() 

    #get a handle to the test database 
    db = connection.test 
    uploads = db.uploads 

    try: 
     query = {'_id': ObjectId(fileId)} 
     cursor = uploads.find(query) 

     for doc in cursor: 
      fileName = doc['fileName'] 
      response = make_response(doc['binFile']) 
      response.headers['Content-Type'] = doc['fileType'] 
      response.headers['Content-Dispostion'] = "attachment; filename="+fileName 
      print response.headers 

     return response 
    except Exception as e: 
     return render_template('Unsuccessful.html') 

私が先にアップロードと私は同じファイル名とデータをファイル(期待通りのMongoDB-作業から取得)をダウンロードすることができるように、私は何をすべきでしょうか?

以下は最近の実行からのログです。 MongoDBのから取得

enter image description here

ファイル(この場合は、「ビッグデータワークフロープレゼンテーション1.pptx」)は、私は、元のファイル名にファイル名を変更してるにもかかわらずのObjectIdファイル名でダウンロードしています。

enter image description here

私はあらゆる細部を欠けている場合は私に知らせてください。私はそれに応じて投稿を更新します。事前に

おかげで、

+0

理由をコメントすることなくdownvoteをクリックするのではなく、理解しやすくするようにしてください。私は可能な限り多くの問題に関する情報を提供しようとしました。 –

+1

ファイル名のラップを試してください: response.headers ['Content-Dispostion'] = "添付ファイル名= \"%s \ ""%fileName –

+0

ご返信ありがとうございます。私はファイル名をラップしようとしましたが、それは同じ問題です。 –

答えて

0

は、あなたの入力のためにあなたに@Bartekジャブロンスキーをありがとうございます。

最後に私はコードを少し微調整してMongoDBに新しいコレクションを作成してこの作業をしました(私はこの時間は幸いでした)。

@app.route('/download/<fileId>', methods = ['GET', 'POST']) 
def download(fileId): 
    connection = pymongo.MongoClient() 

    #get a handle to the nrdc database 
    db = connection.nrdc 
    uploads = db.uploads 

    try: 
     query = {'_id': ObjectId(fileId)} 
     cursor = uploads.find(query) 

     for doc in cursor: 
      fileName = doc['fileName'] 
      response = make_response(doc['binFile']) 
      response.headers['Content-Type'] = doc['fileType'] 
      response.headers["Content-Dispostion"] = "attachment; filename=\"%s\"" %fileName 
     return response 
    except Exception as e: 
#   self.errorList.append("No results found." + type(e)) 
     return False 
関連する問題