django文件上传

-------------------上传图片-------------------
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")

posted on 2016-11-15 00:15  cloud_wh  阅读(207)  评论(0编辑  收藏  举报

导航