django 学习-13 Django文件上传

1、、vim blog/views.py

from django  import  forms
from django.http  import HttpResponse
  1
  2 from django  import  forms
  3 from django.http  import HttpResponse
  4 from django.shortcuts  import render_to_response
  5 class UserForm(forms.Form):
  6         username = forms.CharField()
  7         headImg = forms.FileField()               加入headImg
  8
  9 def register(req):
 10         if req.method  == 'POST':
 11                 uf  = UserForm(req.POST,req.FILES)                    加一个绑定FILES
 12                 if uf.is_valid():
 13                         print uf.cleaned_data['username']
 14                         print uf.cleaned_data['headImg'].name     上传时会显示文件名
 15                         print uf.cleaned_data['headImg'].size        上传时会显示文件大小
 16                         fp = file('/upload/' +uf.cleaned_data['headImg'].name,'wb')    把上传的文件保存到/upload这个目录下
 17                         s = uf.cleaned_data['headImg'].read()                                  

                                          读文件并保存到s里
 18                         fp.write(s)                              
 19                         fp.close()

            return HttpResponse('ok')
 17                         return HttpResponse('ok')
 18         else :
 19                 uf = UserForm()
 20         return render_to_response('register.html',{'uf':uf})

2、vim blog/templates/resgister.html

<!DOCTYPE>
<html>
<head>
        <title></title>
</head>
<body>
<div>
<form method = "post" enctype="multipart/form-data">         要上传文件得加入enctype
{{uf.as_p}}
<input type="submit" value="ok" />
</form>
</div>
</body>
</html>

3、mkdir /upload

4、vim urls.py

url(r'^blog/register/$','blog.views.register'),
                                                                                            
                 

posted @ 2016-01-15 14:31  Lz阿飞  阅读(197)  评论(0编辑  收藏  举报