• Django简单上传文件例子


    URL :

    from django.conf.urls import url
    from app01 import views
    
    urlpatterns = [
        url(r'^upload/', views.upload),
    
    ]

    前端代码 :

    <form action="" method="post" enctype="multipart/form-data">
        {% csrf_token %}
        <input type="file" name="file">
        <input type="submit">
    </form>

    视图代码 :

    import os
    from django.conf import settings
    def upload(request):
        if request.method == "POST":
            filename = request.FILES["file"].name
            #判断名字是否存在
            if os.path.exists(os.path.join(settings.BASE_DIR, filename)):
                #假设文件后缀和文件名以"."区分
                name, suffix = filename.split(".")
                #存在同名文件处理方法
                name += "1"
                filename = name + "." +suffix
            with open(filename, "ab") as f:
                #chunks() 可以指定每次读取的具体大小
                for chunk in request.FILES["file"].chunks():
                    f.write(chunk)
            return HttpResponse("OK")
        return render(request, "file.html")
  • 相关阅读:
    java8
    java8
    java8
    java8
    java8
    java8
    java8
    java8
    GUC-13 生产者和消费者案例-旧
    GUC-14 ForkJoin
  • 原文地址:https://www.cnblogs.com/dong-/p/9787236.html
Copyright © 2020-2023  润新知