上传图片
1.setting.py配置
STATICFILES_DIRS=[
os.path.join(BASE_DIR,'static')
]
UPLOAD_FILES=os.path.join(BASE_DIR,'static/upload')
from django.shortcuts import render,redirect
from django.views import View
import os
from django.conf import settings
from datetime import datetime
from django.http import HttpResponse
from . import models
class UploadView(View):
def get(self,request):
file_path=models.Image.objects.all()
return render(request,'index.html',locals())
# 1.从表单中获取图片文件
def post(self,request):
image = request.FILES.get('img')
# print(image)
# print(image.name)
# print(settings.UPLOAD_FILES)
# 2.生成图片保存路径
fix = datetime.now().strftime('%Y%m%d%H%M%S%f')+'6'
file_path=os.path.join(settings.UPLOAD_FILES,fix+image.name)
#把图片路径写入数据库
models.Image.objects.create(path=image)
# print(fix)
# 3.打开 file_path 文件,并保存文件
f=open(file_path,'wb')
# 保存文件
for buf in image.chunks():
f.write(buf)
# 关闭文件
f.close()
file_path=models.Image.objects.all()
return HttpResponse('OK')
3.模板的代码
注意:1.form的表单应有 enctype=“multipart/form-data” 否则图片显示不出来
2.注意 img 标签中src后面的路径
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<form action="" method="post" enctype="multipart/form-data">
{% csrf_token %}
图片:<input type="file" name="img"><br>
<button type="submit">提交</button>
</form>
{% for i in file_path %}
<img src="/static/upload/{{ i.path }}" alt="图片" width="100" height="100">
{% endfor %}
</body>
</html>
4.注意配置数据库