新建 html 页
app 名称为blog
在templates/blog 下新建 upload.html
Title
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//', views.index02, name='index02'),
path('upload/', views.upload_file, name='upload'),
]
测试
访问 127.0.0.1:8000/blog/upload/
上传文件,文件就会保存到项目下的media/uploads 文件夹