一直以来只要是使用Django框架开发就会遇到前端展示静态图片,除了存在数据库中的图片可以任意的调取之外,往往大多数的做法就是配置static目录,比如:
STATIC_URL = '/static/'
STATICFILES_DIRS = (
os.path.join(BASE_DIR, 'static').replace('\\', '/'),
)
index.html
{% load staticfiles %}
<p><img src="{% static "images.png" %}"></p>
这种就特别常见,可以在前端直接调用static。如果是利用Httprespons返回呢,可以如下:
#settings
STATIC_URL = '/static/'
STATICFILES_DIRS = [
os.path.join(BASE_DIR, 'static')
]
MEDIA_ROOT = os.path.join(BASE_DIR, r'static\images')
#views
def One_page(request):
img = 'myprofile.png'
return render(request, 'profile.html', {"imgs": img})
# urls
from django.conf.urls.static import static
from django.conf import settings
from django.urls import path, re_path
urlpatterns = [
re_path(r'^one_page/$', views.One_page, name='one_page'),
]
urlpatterns += static('/one_page/', document_root=settings.MEDIA_ROOT)
#html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Images</title>
</head>
<body>
<img src="{{imgs}}"/>
</body>
</html>
输入127.0.0.1:8000/one_page/1.jpg 就可以访问到了
看的出来,各种配置,但是这样只能显示static内的图片,那如果是本机上的图片呢,可以将urls换成如下:
from django.views.static import serve
from django.urls import re_path
urlpatterns = [
re_path(r'^img/(?P<path>.*)$', serve, {'document_root':'E:/images'})
]
输入127.0.0.1:8000/img/1.jpg 直接在网页上访问到
如果不使用数据库存储图片,一般都会使用以上的两种方式访问,但是现在有一个问题。假设我不想存数据库、不想配置static的死路径、而且还想展示本机的任意路径的图片,怎么办!那么接下来使用FileResponse方法,如下:
from django.http import FileResponse
from django.utils.http import http_date
import stat
files_path = 'E/images/i.jpg'
statobj = os.stat(files_path)
images(statobj,files_path)
def images(statobj,files_path):
content_type, encoding = mimetypes.guess_type(files_path) # 分析文件的类型或编码
content_type = content_type or 'application/octet-stream' # 指定类型
response = FileResponse(open(files_path, 'rb'), content_type=content_type) # 指定类型打开图片获得响应数据
response["Last-Modified"] = http_date(statobj.st_mtime)
if stat.S_ISREG(statobj.st_mode):
response["Content-Length"] = statobj.st_size # 加入长度
if encoding:
response["Content-Encoding"] = encoding
return response
FileResponse是以流形式返回到前端的,前端可以识别自动下载文件并展示,所以不需要在前端指定值