Django使用HttpResponse返回图片并显示的方法
做了一个关于Django的小案例,想要在网页中显示图片,直接在img标签的src属性写图片的路径是不能显示的,查询资料发现在Django中使用图片这类的资源相当繁琐需要进行一定D的配置,摸索了一会没有整明白,想到了写Java时使用文件流返回图片,于是想到使用该种方式来显示图片。
使用实例如下:
views.py
defmy_image(request,news_id):
d=path.dirname(__file__)
#parent_path=path.dirname(d)
print("d="+str(d))
imagepath=path.join(d,"static/show/wordimage/"+str(news_id)+".png")
print("imagepath="+str(imagepath))
image_data=open(imagepath,"rb").read()
returnHttpResponse(image_data,content_type="image/png")#注意旧版的资料使用mimetype,现在已经改为content_type
urls.py
urlpatterns=[ url(r'^index/$',views.index,name="index"), url(r'^search/$',views.search,name="search"), url(r'^science/(?P.+)/$',views.science,name="science"), url(r'^image/(?P .+)/$',views.my_image,name="image"), ]
temlate:
以上这篇Django使用HttpResponse返回图片并显示的方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持毛票票。
热门推荐
1 训练狗狗憋尿
2 狗狗追踪训练
3 狗狗训练要多少钱
5 深圳狗狗训练
6 训练狗狗唤回
7 狗狗叫怎么训练
8 狗狗训练班
10 狗狗社会化训练
11 狗狗叫回训练
12 广州狗狗训练学校
13 狗狗训练躺下
14 狗狗随行训练
15 训练狗狗巡回
16 狗狗要怎么训练
17 狗狗喂食训练
18 训练狗狗躺下