django图片上传
2018-09-30 本文已影响0人
一念之间789
mysite2/settings.py
#设置图片的保存位置
MEDIA_ROOT = os.path.join(BASE_DIR,"static/media")
image.png
book/models.py
#英雄类
class HeroInfo(models.Model):
...
#英雄图片 默认上传到 dedia文件夹中 将图片放入images中
hpic = mdoels.ImageField(upload_to="images/)
图片上传需要使用form表单 提交类型为post 并加入enctype="multipart/form-data"
book/hero_add.html
<form action="{% url "book:hero_add" %}" method="post" enctype="multipart/form-data">
图片:<input name="hpic" type="file"><br/>
book/views.py
#利用UUID生成不重复的图片名,避免上传相同的名字的图片被覆盖
def do_file_name(file_name):
return str(uuid.uuid1())+os.path.splitext(file_name)[1]
def hero_add(request):
...
hpic = request.FILES["hpic"]
# 审核上传文件大小 超过30K不能上传
if hpic.size > 1024 * 30:
return render(request, "book/hero_add.html", {"error_link": "文件最大不超过30K"})
# 保存到本地
hpic_chunks = hpic.chunks()
# 文件保存的路径
file_name = os.path.join("images", do_file_name(hpic.name))
file_path = os.path.join(settings.MEDIA_ROOT, file_name)
# 写
with open(file_path, "wb")as file:
for chunk in hpic_chunks:
file.write(chunk)
hero = HeroInfo()
...
hero.hpic = file_name
hero.save()
return render(request, "book/hero_add.html",{"ok_link": "已添加成功,你可以继续添加或返回英雄列表页"})