1. 程式人生 > >Python Django使用HttpResponse返回圖片並顯示

Python Django使用HttpResponse返回圖片並顯示

views

# 1.03 讀取圖片demo
def read_img(request):
    """
    : 讀取圖片
    :param request:
    :return:
    """
    try:
        data = request.GET
        file_name = data.get("file_name")
        imagepath = os.path.join(settings.BASE_DIR, "static/resume/images/{}".format(file_name))  # 圖片路徑
        with open(imagepath, 'rb') as f:
            image_data = f.read()
        return HttpResponse(image_data, content_type="image/png")
    except Exception as e:
        print(e)
        return HttpResponse(str(e))
url('
url(r'^image/(?P<news_id>.+)/$',views.my_image,name="image"),

', views.read_img, name='read_img'), # 1.03 讀取img demo
url(r'^read_img/(?P<news_id>.+)/$',views.my_image,name="image"),

template

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