Django—文件上传

  • 配置


    1.表单注意
    表单的enctype的值需要设置为:enctype="multipart/form-data
    表单提交类型为POST
    
    
    2.存储路径
    在settings.py⽂件下添加如下代码
    #设置上传⽂件路径
    MDEIA_ROOT = os.path.join(BASE_DIR,'static/upload')
    
    3. ⽂件上传对象的属性和⽅法
    名称 说明
    file.name 获取上传的名称
    file.size 获取上传⽂件的⼤⼩(字节)
    file.read() 读取全部(适⽤于⼩⽂件)
    file.chunks() 按块来返回⽂件 通过for循环进⾏迭代,可以将⼤⽂
    件按照块来写⼊到服务器
    file.multiple_chunks() 判断⽂件 是否⼤于2.5M 返回True或者False
  • 实现


    <!DOCTYPE html>
    <html lang="en"> <head>
     <meta charset="UTF-8">
     <title>Title</title>
    </head> <body> <form action="/doUpload/" method="post" enctype="multipart/formdata">
     {% csrf_token %}
     <p>⽂件 <input type="file" name="file"></p>
    <p><input type="submit" value="上传"></p>
    </form>
    </body>
    </html>
    # views.py
    from django.conf import settings
    import os
    #⽂件上传处理
    def doUpload(req):
     file = req.FILES.get('file')
     # print(file.name)
     # print(file.size)
     savePath = os.path.join(settings.MDEIA_ROOT,file.name)
     # print(savePath)
     with open(savePath,'wb') as f:
     # f.write(file.read())
     if file.multiple_chunks():
     for myf in file.chunks():
     f.write(myf)
     print('⼤于2.5')
     else:
     print('⼩于2.5')
     f.write(file.read())
     return HttpResponse('⽂件上传')
发布了199 篇原创文章 · 获赞 6 · 访问量 2431

猜你喜欢

转载自blog.csdn.net/piduocheng0577/article/details/105031397