form 表单注意事项:
1. 提交按钮要使用 submit!!!
2.input 要写在 form 表单里面, input 要有 name 属性
3.form 标签要加 action 和 method, 如果有文件的话还要加一个 enctype 这个属性
文件上传:
urls.py
- from django.contrib import admin
- from django.urls import path
- from app01 import views
- urlpatterns = [
- path('admin/', admin.site.urls),
- path('upload/', views.upload),
- ]
views.py
- from django.shortcuts import render
- # Create your views here.
- def upload(request):
- if request.method == "POST":
- print(request.POST)
- #拿到的是一个文件对象 注意上传文件 对应的获取方法 是 FILES
- file_obj = request.FILES.get("file")
- with open(file_obj.name,"wb") as f:
- for line in file_obj:
- f.write(line)
- return render(request,'upload.html')
upload.HTML
- <!DOCTYPE HTML>
- <HTML lang="zh-CN">
- <head>
- <meta charset="UTF-8">
- <title>
- Title
- </title>
- <meta name="viewport" content="width=device-width, initial-scale=1">
- {% load static %}
- <link rel="stylesheet" href="{% static'bootstrap/CSS/bootstrap.min.css'%}">
- <link rel="stylesheet" href="{% static'fontAwesome/css/font-awesome.min.css'%}">
- <link rel="stylesheet" href="{% static'sweetalert/sweetalert.css'%}">
- </head>
- <body>
- // 注意: 只要时上传文件的 都要有 enctype="multipart/form-data"
- <form action="/upload/" method="post" enctype="multipart/form-data">
- {% csrf_token %}
- <p>
- 文件:
- <input type="file" name="file">
- </p>
- <p>
- <input type="submit" value="提交">
- </p>
- </form>
- <script src="{% static'jquery-3.2.1.min.js'%}">
- </script>
- <script src="{% static'setupajax.js'%}">
- </script>
- <script src="{% static'bootstrap/js/bootstrap.min.js'%}">
- </script>
- <script src="{% static'sweetalert/sweetalert.min.js'%}">
- </script>
- <script src="{% static'gt.js'%}">
- </script>
- </body>
- </HTML>
示例二:
- def upload(request):
- """
- 保存上传文件前, 数据需要存放在某个位置. 默认当上传文件小于 2.5M 时, django 会将上传文件的全部内容读进内存. 从内存读取一次, 写磁盘一次.
- 但当上传文件很大时, django 会把上传文件写到临时文件中, 然后存放到系统临时文件夹中.
- :param request:
- :return:
- """ if request.method =="POST":
- # 从请求的 FILES 中获取上传文件的文件名, file 为页面上 type=files 类型 input 的 name 属性值
- filename = request.FILES["file"].name
- # 在项目目录下新建一个文件
- with open(filename, "wb") as f:
- # 从上传的文件对象中一点一点读
- for chunk in request.FILES["file"].chunks():
- # 写入本地文件
- f.write(chunk)
- return HttpResponse("上传 OK")
上传文件
来源: http://www.bubuko.com/infodetail-3509106.html