1、View
# ImageFile类继承File类,扩展了width和height属性
file_hpic = ImageFile(request.FILES["hpic"])
# 检查文件的格式、大小、宽高
if file_hpic.name.endswith(".jpg") and round(file_hpic.size / 1024, 1) <= 300 \
and 200 <= file_hpic.width <= 300 and 200 <= file_hpic.height <= 300:
# 对图片进行编号
file_name = str(uuid.uuid1()) + os.path.splitext(file_hpic.name)[1]
file_path = os.path.join(settings.MEDIA_ROOT, "book", file_name)
# 文件上传1--上传到服务器
with open(file_path, "wb") as file:
for chunk in file_hpic.chunks():
file.write(chunk)
# 文件上传2--写入到数据库中
hero.hpic = os.path.join("book", file_name)
2、Template
<input type="file" name="hpic"/>
3、备注
上传的图片文件夹配置,需要在项目目录的settings.py文件添加:
MEDIA_ROOT = os.path.join(BASE_DIR, 'static/media')
网友评论