在MongoDB中保存和获取Blob数据

0 投票
1 回答
2165 浏览
提问于 2025-04-18 16:42

我正在尝试做一件很简单的事情,就是使用django_mongodb_engine把文件保存到mongodb集合里,但我遇到了很多困难。

到目前为止,我只能通过先把文件转换成base64格式,然后再存到数据库里,取出来的时候再把它解码成原来的样子来实现这个功能。我不想这样做,因为来回转换成base64可能会占用比实际操作更多的资源,虽然我也可能是错的。

所以,有人能告诉我用django_mongodb_engine正确保存和获取MongoDB中的二进制数据的方法吗?

到目前为止的代码:

models.py

from django.db import models
from djangotoolbox.fields import *

class TestModel(models.Model):
    name = models.CharField(max_length=50)
    zip_file = BlobField()

views.py

from django.shortcuts import render
from django.http import HttpResponse
from my_project.models import *

def index(request):
    f = open('myfile.zip')
    contents = f.read()
    f.close()

    record = TestModel.objects.create(
        name = "My File",
        zip_file = contents
    )

    result = TestModel.objects.filter(name = "My File")

    zip_contents = result[0].zip_file

    response = HttpResponse(zip_contents, content_type='application/zip')
    response['Content-Disposition'] = 'attachment; filename="My_File.zip"'
    return response

哦,顺便说一下,请不要告诉我使用GridFS,因为我存储的文件大小远小于16MB,最多也就2.5MB到3.5MB。

1 个回答

0

正如NeilLunn提到的,django_mongodb_engine不支持二进制数据字段,所以最好直接使用mongoengine的ORM(对象关系映射)。

以下是我能正常运行的代码:

models.py

from mongoengine import *

class TestModel(Document):
    name = StringField(max_length=50)
    zip_file = BinaryField()

views.py

from django.http import HttpResponse
from my_project.models import *

def index(request):
    f = open('myfile.zip')
    contents = f.read()
    f.close()

    record = TestModel(name = 'My File', zip_file = contents)
    record.save()

    result = SkinDetails.objects(name='Metro Skin')

    zip_contents = result[0].zip_file

    response = HttpResponse(zip_contents, content_type='application/zip')
    response['Content-Disposition'] = 'attachment; filename="My_File.zip"'
    return response

撰写回答