1 注意
这里需要注意两个地方:
表单提交方式需要是 post
form 添加一个属性为 enctype=“multipart/form-data”
form的action,路由,views.py要保持一致
urlpatterns = [
path('', views.index),
path('index2', views.index2),
]
from PIL import Image
@csrf_exempt #取消csrf验证
def index(req):
return render(req, "index.html")
def index2(req):
print("前端数据: ", req.POST)
print("file:", req.FILES)
for item in req.FILES:
obj = req.FILES.get(item) # 获取要写入的文件
filename = obj.name # 获取文件名
f = open("C:\\Users\\88304\\Desktop\\Division1\\Retina-Unet-1\\qianduantupian\\01_test.png", 'wb')
for line in obj.chunks(): # 分块写入
f.write(line)
f.close()
return render(req, 'FG.html')
跳转:
<form action="/index2" method="POST" enctype="multipart/form-data">
{% csrf_token %}
2 在 index.html 加入input 标签
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1>hello worlds</h1>
<form action="/klvchen/" method="post" enctype="multipart/form-data">
<p><input type="file" name="upload"></p>
<p><input type="submit" value="submit"></p>
</form>
</body>
</html>
3 修改 views.py
from django.shortcuts import render
def klvchen(req):
print("前端数据: ", req.POST)
print("file:", req.FILES)
for item in req.FILES:
obj = req.FILES.get(item) # 获取要写入的文件
filename = obj.name # 获取文件名
f = open(filename, 'wb')
for line in obj.chunks(): # 分块写入
f.write(line)
f.close()
return render(req, "index.html")
成功上传文件