upload.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>上传页面</title>
</head>
<body>
<form action="/upload/" method="post" enctype="multipart/form-data">
<input type="file" name="upload_file">
<input type="submit" value="上传">
</form>
</body>
</html>
urls.py:
from django.conf.urls import url
from app01 import views
urlpatterns = [
url(r'^upload/', views.upload),
]
views.py:
from django.shortcuts import render, HttpResponse
# 上传
def upload(request):
if request.method == "POST":
# upload_file 为 input 中的 name 属性值
filename = request.FILES["upload_file"].name # 获取上传的文件的文件名
# 在项目目录下创建上传的文件
with open(filename, "wb") as f:
# 从上传的文件对象中一点一点读
for chunk in request.FILES["upload_file"].chunks():
f.write(chunk) # 写入本地文件
return HttpResponse("上传OK")
else:
return render(request, "upload.html")
运行结果:
选择一个图片,上传
上传成功
在根目录下可以看到上传的文件