Question

I am trying to get a file out of GridFS in MongoDB and allow the user to download a zip archive with it using Django.

My function in my views.py file looks like this:

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)

Whenever I call this function (I am doing so through a GET request using urllib2.openurl() in a terminal), it outputs the contents of the file onto the terminal. However, I want it to allow me to download a zip archive containing this file.

I have been looking at many examples, but I can't figure out where I am going wrong.

Thank you in advance for any help you can give me.

Was it helpful?

Solution

Please check Serving large files ( with high loads ) in Django on sending files to client. Also, you seem to be reading directly from chunk collection by doing a find_one and that is no appropriate way to use files stored on GridFS. Ideally, you would access it using gridfs file io api:

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

Also you may want to return response directly in the try block if all is successful instead of wrapping again in HttpReponse.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top