form表单注意事项:
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>
示例二:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
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")
上传文件