您的位置:首页 > 理论基础 > 计算机网络

Django使用HttpResponse返回图片并显示

2017-05-03 20:31 495 查看
做了一个关于Django的小案例,想要在网页中显示图片,直接在img标签的src属性写图片的路径是不能显示的,查询资料发现在Django中使用图片这类的资源相当繁琐需要进行一定D的配置,摸索了一会没有整明白,想到了写Java时使用文件流返回图片,于是想到使用该种方式来显示图片。使用实例如下:

views.py

def my_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()
return HttpResponse(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<news_id>.+)/$', views.science,name="science"),
url(r'^image/(?P<news_id>.+)/$',views.my_image,name="image"),
]


temlate:
<img src="{% url 'show:image' param.id %}" alt="{{param.id}}"/>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: