【问题标题】:Display images in django web app from mongo db从 mongo db 在 django web 应用程序中显示图像
【发布时间】:2016-01-07 05:33:51
【问题描述】:

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

我的模型.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

我的意见.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 网页中显示这些数据?

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

【问题讨论】:

    标签: python html django mongodb pymongo


    【解决方案1】:

    您可能可以使用“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 或其他必要的内容)。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-07-19
      • 2017-06-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多