新建 html 页
app 名称为blog
在templates/blog 下新建 upload.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<div class="row">
<div class="col-md-8 col-md-offset-2">
<form class="form-inline" role="form" method="post" enctype="multipart/form-data" accept-charset="utf-8">
{% csrf_token %}
<div class="form-group">
<input type="file" name="file">
</div>
<div class="form-group">
<input type="submit" value="上传文件">
</div>
</form>
</div>
</div>
</body>
</html>
blog 下 views.py 中添加处理方法
import os
from django.http import HttpResponse,Http404
from django.shortcuts import render
# 处理上传上来文件的方法,
def upload_file(request):
if request.method=="POST":
handle_upload_file(request.FILES['file'],str(request.FILES['file']))
return HttpResponse('Successful')
return render(request,'blog/upload.html')
# 文件保存到指定路径
def handle_upload_file(file,filename):
path='media/uploads/'
if not os.path.exists(path):
os.makedirs(path)
with open(path+filename,"wb+")as dest:
for chunk in file.chunks():
dest.write(chunk)
编写 urls.py 增加路由
from django.urls import path,include
from . import views
app_name = 'blog'
urlpatterns = [
path('', views.index, name='index'),
path('index01/', views.index01, name='index01'),
path('index02/<int:author_id>/', views.index02, name='index02'),
path('upload/', views.upload_file, name='upload'),
]
测试
访问 127.0.0.1:8000/blog/upload/
上传文件,文件就会保存到项目下的media/uploads 文件夹
网友评论