背景:
页面,通过按钮上传本地文件到服务器;
下载服务器上的文件到本地
URL配置
# 创建app
python3 manager startapp app_name
# 在总urls配置地址
from django.conf.urls import include
urlpatterns = [
path('file/', include('app_name.urls'))
]
# 在app_name app 下,配置url
from . import views
urlpatterns = [
path('upload/', views.upload_file, name='upload'),
path('download/', views.download_file, name='download'),
]
编写views
from django.views.decorators.csrf import csrf_exempt
from django.views.decorators.http import require_http_methods
from django.http import StreamingHttpResponse
def handle_uploaded_file(f):
# 文件被上传到path 地址 上
name = f.name
with open(path, 'wb') as destination:
for hunk in f.chunks():
destination.write(chunk)
@csrf_except
@require_http_methods(['POST'])
def upolad_file(request):
# django 前端通过 form-data file 上传文件,文件存在request.FILES中
# 可以在form中配置文件上传类型,下面会编写form
form = UploadFileForm(request.FILES)
if form.is_valid():
handle_uploaded_file(request.FILES['file'])
return JsonResponse({'status': 'success', 'code': 200})
else:
return JsonResponse(form.errors)
def download_file(request):
form = DownFileForm(request.GET)
def file_iterator(file_name, chunk_siza=512):
with open(file_name, 'rb') as f:
while True:
c = f.read(chunk_size)
if c:
yield c
else:
break
if form.is_valid():
file_name = os.path.join(seetting.DOWNLOAD_ROOT, form.clean_data['file_name'])
response = StreamingHttpResponse(file_iterator(file_name))
response['Content-Type'] = 'application/octet-stream'
response['Content-Disposition'] = 'attachment; filename="{}"'.format(file_name)
return response
else:
return JsonResponse(form.errors)
编写form
from django import forms
class UploadFileForm(forms.Form):
file = forms.FileField()
def clean_file(self):
file = self.cleaned_data['file']
ext = file.name.split('.')[-1].lower()
if ext not in ['xls', 'xlsx']:
raise forms.ValidationError("只能上传excel文件")
return file
总结:
还是要看文档,web 简单来说就是请求,响应,平时还是要多写