Django-上传图片
1. 模型定义中将属性定义成 models.ImageField 类型
pic=models.ImageField(upload_to='cars/')
2. 图片存储路径--settings.py 文件中增加 media_root 项
MEDIA_ROOT=os.path.join(BASE_DIR,"static/media")
3. html模板
<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>
form表单中一定要加enctype="multipart/form-data"
multipart/form-data是将文件以二进制的形式上传,这样可以实现多种类型的文件上传
4. 视图代码-处理函数
引用模块
from django.conf import settings
def upload(request):
if request.method == "POST":
f1 = request.FILES['pic']
fname = '%s/%s' % (settings.MEDIA_ROOT, f1.name)
with open(fname, 'wb+') as pic:
for c in f1.chunks():
pic.write(c)
return HttpResponse("ok")
else:
return HttpResponse("error")
5. 应用url配置
url(r'^upload/$', views.upload)