簡體   English   中英

Django:提供文件以供從mongodb中的GridFS下載

[英]Django: Serve file for download from GridFS in mongodb

我正在嘗試從MongoDB中的GridFS中獲取文件,並允許用戶使用Django下載zip存檔。

我的views.py文件中的函數如下所示:

def GetFile(request, md5):
    try:
        fs = gridfs.GridFS(db)

        f = db.fs.files.find_one({"md5": md5})

        if f:
            fileID = f['_id']
            filename = f['filename']

            if fileID:
                doc = db.fs.chunks.find_one({"files_id": fileID})

                if doc:
                    data = doc['data']
                    myFile = cStringIO.StringIO(data)
                    response = HttpResponse(FileWrapper(myFile), content_type = 'application/zip')
                    response['Content-Transfer-Encoding'] = 'Binary'
                    response['Content-Disposition'] = "attachment; filename=%s" % filename

    except:
        response = "It didn't work!"

return HttpResponse(response)

每當我調用此函數時(在終端中使用urllib2.openurl()通過GET請求進行此操作),它將把文件的內容輸出到終端上。 但是,我希望它允許我下載包含此文件的zip存檔。

我一直在看很多例子,但是我不知道哪里出了問題。

預先感謝您能給我的任何幫助。

在將文件發送到客戶端時,請選中在Django中服務大型文件(高負載) 另外,您似乎通過執行find_one直接從塊集合中讀取數據,這不是使用存儲在GridFS上的文件的適當方法。 理想情況下,您將使用gridfs文件io api訪問它:

response = HttpResponse(FileWrapper(fs.get_version(filename)), content_type = 'application/zip')
response['Content-Transfer-Encoding'] = 'Binary'

另外,如果一切成功,您可能希望直接在try塊中返回響應,而不是再次包裝在HttpReponse中。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM