【问题标题】:Django: Serve file for download from GridFS in mongodbDjango:服务文件以从 MongoDB 中的 GridFS 下载
【发布时间】:2014-02-26 14:49:04
【问题描述】:

我正在尝试从 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 存档。

我查看了很多示例,但我不知道哪里出错了。

提前感谢您能给我的任何帮助。

【问题讨论】:

    标签: python django mongodb download gridfs


    【解决方案1】:

    请检查Serving large files ( with high loads ) in 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 中再次包装。

    【讨论】:

      猜你喜欢
      • 2020-08-12
      • 2012-06-29
      • 1970-01-01
      • 2012-11-10
      • 1970-01-01
      • 1970-01-01
      • 2019-11-11
      • 2012-03-22
      • 1970-01-01
      相关资源
      最近更新 更多