• Django 上传文件


    setting.py:

    MEDIA_ROOT = os.path.join(BASE_DIR,r'staticupfile')

    urls.py:

    url(r'^upfile/$',views.upfile),
    url(r'^savefile/$',views.savefile),

     views.py:

    def upfile(request):
        return render(request,'myApp/upfile.html')
    def savefile(request):
        if request.method == "POST":
            f = request.FILES['file']
            filePath = os.path.join(settings.MEDIA_ROOT,f.name)
            with open(filePath,'wb') as fp:
                for info in f.chunks():
                    fp.write(info)
            return HttpResponse("上传成功")
        else:
            return HttpResponse("上传失败")

    upfile.html:

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>上传文件</title>
    </head>
    <body>
        <form action="/sunck/savefile/" method="post" enctype="multipart/form-data">
            {% csrf_token %}
            <input type="file" name="file">
            <input type="submit" value="上传">
        </form>
    </body>
    </html>

    1.在项目setting.py配置MEDIA_ROOT = os.path.join(BASE_DIR,r'staticupfile'),BASE_DIR代表项目目录,然后在项目目录下手动创建/static/upfile

    2.url进入到/sunck/upfile,显示(上传文件的请求方式一定是post)

    3.选择文件后点击上传,提交到/sunck/savefile,然后执行对应的视图函数,将文件保存到设置好的路径(filePath = os.path.join(settings.MEDIA_ROOT,f.name))

    笔记:

    1.f = request.FILE['file']里的file就是<input type="file" name="file">里的name属性值

    2.f.chunks()是上传文件的内容

    3.要以‘wb’(二进制写入)的方式打开,‘w’不行

  • 相关阅读:
    有向无环图单源最短路径问题
    linux下程序编译出错解决方法
    Ceres入门笔记
    Java 中的数据结构类 Vector 和 ArrayList
    102. Binary Tree Level Order Traversal
    104. Maximum Depth of Binary Tree
    101. Symmetric Tree
    100. Same Tree
    490. The Maze
    骑士游历问题
  • 原文地址:https://www.cnblogs.com/hooo-1102/p/11971348.html
Copyright © 2020-2023  润新知