Django使用HttpResponse返回图片并显示 Django使用HttpResponse返回图片并显示的方法

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

Django使用HttpResponse返回图片并显示 Django使用HttpResponse返回图片并显示的方法

Lavi_qq_2910138025   2021-03-31 我要评论

做了一个关于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"), 
  <strong>url(r'^image/(?P<news_id>.+)/$',views.my_image,name="image"),</strong> 
] 

temlate:

<img src="{% url 'show:image' param.id %}" alt="{{param.id}}"/> 

以上这篇Django使用HttpResponse返回图片并显示的方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持。

猜您喜欢

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们