在django框架中,前端页面不能直接使用相对路径或绝对路径显示图片,需要通过urls.py来提供每个URL 对应的django的函数来显示在页面 。
思路:将form表单上传的文件,后台接受后创建文件夹接受并存储到数据库中,我的图片路径存储在D:\workspace\upload_pic\media,然后新建一个文件存放在里边,上传成功后返回图像
新建一个数据表
model.py
from django.db import models
class imginfo(models.Model):
img = models.FileField(upload_to='media')
urls.py
from django.contrib import admin
from django.urls import path, re_path
from app01 import views
from django.views.static import serve #图片显示
urlpatterns = [
path('admin/', admin.site.urls),
path('index/', views.index),
re_path('media/(?P<path>.*)$', serve, {'document_root': r'D:\workspace\upload_pic\media'}),
#这句意思是将访问的图片href由“http://127.0.0.1:8888/media/图片存储文件夹/字母哥.jpg”转为本地访问D:\workspace\upload_pic\media的形式
path('login/', views.login),
]
在setting.py 里边添加以下代码,为了创建文件
STATICFILES_DIRS = [
os.path.join(BASE_DIR, 'static'),
os.path.join(BASE_DIR, 'media').replace('\\', '/'),
]
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
views.py的代码
from django.shortcuts import render, HttpResponse
from django.conf import settings #导入settings
import os #创建文件夹需要的包
from app01 import models
# Create your views here.
#
def index(request):
if request.method == 'POST':
img = request.FILES.get('img')
path = settings.MEDIA_ROOT
file = '图片存储文件夹'
pic_path = path + '/' + file
print(pic_path)
isExists = os.path.exists(pic_path) # 路径存在则返回true,不存在则返回false
if isExists:
print("目录已存在")
else:
os.mkdir(pic_path)
print("创建成功")
img_url = pic_path + '/' + img.name
print(img_url)
with open(img_url, 'wb') as f: #将图片以二进制的形式写入
for data in img.chunks():
f.write(data)
pic_data = 'http://127.0.0.1:8888/media' + '/' + 'file' + img.name
#将路径转化一下,转为href的形式,然后存入数据库,发到后端
models.imginfo.objects.create(img=pic_data) #生成一条数据
img_href = models.imginfo.objects.filter(id=1)[0]
#将id为1的数据取出
print(img_href)
return render(request, 'login.html', {'img_href': img_href})
return render(request, 'index.html')
def login(request):
return render(request, 'login.html')
index.html
<h1>图片上传页面</h1>
<form action="" method="post" enctype="multipart/form-data">
{% csrf_token %}
<p><input type="file" name="img" /></p>
<p><input type="submit" value="提交"></p>
</form>