在 mongo db 的 django web 应用程序中显示图像

Display images in django web app from mongo db

我正在尝试在来自 mongodb 的 django html 网页中显示图像。 我使用带有 vendor_id 作为额外值的 gridfs 将图像保存在 mongodb 中。 然后我像这样检索它们:

我的models.py:

def getImages(self, vendor_id):
    img_name = []
    img_ids = []
    images = []
    for each in self.files.find({'vendor_id':vendor_id}):   ####self.files is a variable which store value db['fs.files']
        img_ids.append(each['_id'])
        img_name.append(each['name'])

    for iid in img_ids:
        images.append(self.gfs.get(iid).read())

    return images

我的views.py:

def vendorData(request):
    vendors = Vendors()
    if request.method == 'GET':
        vendor_id = request.GET.get('vendor_id')
        if vendors.checkValidVendorId(vendor_id) == False:
            return HttpResponse('Invalid Vendor Id.')
        else:
            vendor_details = vendors.getVendorDetails(vendor_id)
            vendor_name = vendor_details[0]
            restaurant_name = vendor_details[1]
            images = vendors.getImages(vendor_id)
            context_dict = {'vendor_id':vendor_id,
                            'vendor_name':vendor_name,
                            'restaurant_name':restaurant_name
                            'images':images}
            return render(request, 'vendor_data.html', context_dict)

我把多张图片的二进制数据传给了一个列表中的views.py。 如何在django网页中显示这些数据?

注意:我可以通过临时保存来显示这些图像。但是有没有其他方法可以在不保存的情况下显示这些图像?

您或许可以使用 "data" uri 格式,它允许您将图像作为 base64 编码的字符串传递。当然,您需要先在 getImages 函数中对图像进行编码:

for iid in img_ids:
    images.append(base64.b64encode(self.gfs.get(iid).read()))

并且在模板中可以直接输出数据:

{% for image in images %}
    <img src="data:image/png;base64,{{ img }}">
{% endfor %}

(显然,将 png 替换为 jpg 或其他必要的内容)。