[英]Display images in django web app from mongo db
I am trying to display images in django html web page from mongodb. 我正在尝试从mongodb在django html网页中显示图像。 I saved images in mongodb using gridfs with vendor_id as an extra value.
我将gridfs和vendor_id作为额外值保存在mongodb中。 Then i retrieved them like :
然后我像检索它们:
my models.py: 我的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
my views.py: 我的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)
I passed the binary data of multiple images to views.py in a list. 我将多个图像的二进制数据传递给列表中的views.py。 How to show this data in django web page?
如何在django网页中显示此数据?
Note: I can show these images by saving them temporarily. 注意:我可以通过暂时保存来显示这些图像。 But is there any other way i can display these images without saving?
但是还有其他方法可以显示这些图像而无需保存吗?
You could probably use the "data" uri format, which allows you to pass the image as a base64-encoded string. 您可能会使用“数据” uri格式,该格式允许您将图像作为base64编码的字符串传递。 Of course, you'll need to encode the images first in your
getImages
function: 当然,您首先需要在
getImages
函数中对图像进行编码:
for iid in img_ids:
images.append(base64.b64encode(self.gfs.get(iid).read()))
and in the template you can output the data directly: 在模板中,您可以直接输出数据:
{% for image in images %}
<img src="data:image/png;base64,{{ img }}">
{% endfor %}
(obviously, replace png with jpg or whatever as necessary). (显然,将png替换为jpg或其他必要内容)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.