zoukankan      html  css  js  c++  java
  • 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'),
                                                                                                
                     

  • 相关阅读:
    zzuli--2134: 维克兹的进制转换(规律)
    hdu--1316--How Many Fibs?(java大数)
    NYOJ--517--最小公倍数(大数打表)
    NYOJ--513--A+B Problem IV(大数)
    NYOJ--45--棋盘覆盖(大数)
    NYOJ--114--某种序列(大数)
    HAUT--1262--魔法宝石(暴力)
    NYOJ--1276--机器设备(河南省第九届省赛,简单的bfs)
    hdu--1429--胜利大逃亡(续) (bfs+状态压缩)
    NYOJ--541--最强DE 战斗力(递推)
  • 原文地址:https://www.cnblogs.com/Icanflyssj/p/5133244.html
Copyright © 2011-2022 走看看