首页技术文章正文

django文件上传

更新时间:2018-08-09 来源:黑马程序员 浏览量:

1、model中定义属性类型为models.ImageField类型
pic=models.ImageField(upload_to='images/upload/')

2、如果属性类型为ImageField需要安装包Pilow
pip install Pillow==3.4.1

3、图片存储路径
1、在项目根目录下创建static文件夹

2、图片上传后,会被保存到“/static/images/upload/图片文件”

3、打开settings.py文件,增加media_root项
MEDIA_ROOT=os.path.join(BASE_DIR,"static")

4、使用django后台管理,遇到ImageField类型的属性会出现一个file框,完成文件上传

5、实例:
<html>
<head>
<title>文件上传</title>
</head>
<body>
<form method="post" action="upload/" enctype="multipart/form-data">
<input type="text" name="title"><br>
<input type="file" name="pic"/><br>
<input type="submit" value="上传">
</form>
</body>
</html>

#-------------后台view接收处理
def upload(request):
if request.method == "POST":
f1 = request.FILES['pic']
fname = '/static/images/upload/%s' % f1.name
with open(fname, 'w') as pic:
for c in f1.chunks():
pic.write(c)
return HttpResponse("ok")
else:
return HttpResponse("error")



作者:黑马程序员人工智能+python培训学院
首发:http://python.itheima.com/

分享到:
在线咨询 我要报名
和我们在线交谈!