settings.py文件
# 配置文件上传路径
MEDIA_ROOT = os.path.join(BASE_DIR, 'media\\')
# 配置模板路径
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR, 'templates')], # BASE_DIR 这个是sttings.py配置文件起头配置好了的。‘BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))’大概在16行左右
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
views.py文件
from django.shortcuts import render, redirect
from django.http import HttpResponse
from django.conf import settings
import time,os
def showUpload(request):
"""上传"""
return render(request, 'myapp/upload.html')
def upload(request):
if request.method == "POST":
myfile = request.FILES.get('pic',None)
try:
suffix = str(myfile.name.split('.')[-1])
times = str(time.time()).split('.').pop() # 生成时间戳,取小数点后的值
fil = str(myfile.name.split('.')[0])
filename = times + '_' + fil + '.' + suffix
filename_dir = settings.MEDIA_ROOT
with open(filename_dir+filename, 'wb+') as destination:
for chunk in myfile.chunks():
destination.write(chunk)
destination.close()
except:
return HttpResponse("提交失败")
else:
return redirect('showUpdate')
return HttpResponse('上传成功')
remplates/upload.html文件
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<form action="{% url 'upload' %}" method="POST" enctype="multipart/form-data">
{% csrf_token %}
<input type="file" name="pic">
<input type="submit" value="提交">
</form>
</body>
</html>
?app/urls.py
path('upload/', views.upload, name="upload"), #用于发送文件上传请求
path('showUpload/', views.showUpload, name="showUpload"), # 用于加载模板视图
|