模板文件
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<div>
<form action="/home" method="post" enctype="multipart/form-data">
{# 添加以下语句 #}
{% csrf_token %}
<p>
<input type="file" name="file">
<input type="submit" value="提交">
</p>
</form>
</div>
</body>
</html>
注意:form 表单里有一句 enctype=”multipart/form-data”,在上传文件的表单里必须要有这个。enctype 属性规定在发送到服务器之前应该如何对表单数据进行编码。
视图函数
def home(request):
# 判断是否是POST提交
if request.method == 'POST':
# 通过文件名字取文件
file = request.FILES.get('file')
import os
# 拼接文件路径,名字
file_path = os.path.join('upload', file.name)
# 打开这个文件, 模式为二进制模式读写打开
f = open(file_path, mode='wb')
# 写到指定文件中
for i in file.chunks():
f.write(i)
# 关闭文件流
f.close()
return render(request, 'home.html')
如果出现Django提交表单报错-CSRF token missing or incorrect.
请看:http://gaocaishun.cn/819.html
更多内容请看个人站点:http://www.gaocaishun.cn