模板
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
{{ dict_info }}
<form enctype="multipart/form-data" action="{% url 'upload' %}" method="POST">
<input type="file" name="upload" required/>
<input type="submit" value="上传"/>
</form>
</body>
</html>
路由
from django.urls import path, include, re_path
import blog.views
urlpatterns = [
re_path('upload', blog.views.upload_head, name='upload')
]
视图
def upload_head(request):
if request.method == 'POST':
my_file = request.FILES.get('upload', None)
if not my_file:
return render(request, 'upload.html', {'dict_info': '没有上传内容'})
position = os.path.join('upload', my_file.name)
with open(position, 'wb') as file_object:
for storage in my_file.chunks():
file_object.write(storage)
return render(request, 'upload.html', {'dict_info': '上传完成'})
return render(request, 'upload.html')