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'),
                                                                                                
                     

  • 相关阅读:
    Linux du命令
    log
    为什么基址不会变?
    游戏辅助分类
    什么是nProtect?
    Linux启动过程详解
    Restorator 2018 v3.90汉化注册版 含注册码汉化激活教程
    LoadLibrary(C:softIDA 7.0IDA 7.0pluginspython64.dll) error: 找不到指定的模块。 C:softIDA 7.0IDA 7.0pluginspython64.dll: can't load file LoadLibrary(C:softIDA 7.0IDA 7.0pluginspython64.dll) erro
    windows 安装python2.7
    ida 下载
  • 原文地址:https://www.cnblogs.com/Icanflyssj/p/5133244.html
Copyright © 2011-2022 走看看