Python 在mongo db的django web应用程序中显示图像
我试图在mongodb的django html网页中显示图像。 我在mongodb中使用gridfs保存了图像,并将供应商id作为额外值。 然后我像这样检索它们: my models.py:Python 在mongo db的django web应用程序中显示图像,python,html,django,mongodb,pymongo,Python,Html,Django,Mongodb,Pymongo,我试图在mongodb的django html网页中显示图像。 我在mongodb中使用gridfs保存了图像,并将供应商id作为额外值。 然后我像这样检索它们: my models.py: def getImages(self, vendor_id): img_name = [] img_ids = [] images = [] for each in self.files.find({'vendor_id':vendor_id}): ####self.fi
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
my 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网页中显示此数据
注意:我可以通过临时保存来显示这些图像。但是有没有其他方法可以显示这些图像而不保存?您可能可以使用“数据”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 %}
{%用于图像中的图像%}
{%endfor%}
(显然,用jpg或任何必要的格式替换png)。您可能会使用“数据”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 %}
{%用于图像中的图像%}
{%endfor%}
(显然,用jpg或任何必要的格式替换png)。您可能会使用“数据”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 %}
{%用于图像中的图像%}
{%endfor%}
(显然,用jpg或任何必要的格式替换png)。您可能会使用“数据”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 %}
{%用于图像中的图像%}
{%endfor%}
(显然,用jpg或任何必要的东西替换png)