背景:

页面,通过按钮上传本地文件到服务器;
下载服务器上的文件到本地

URL配置

  1. # 创建app
  2. python3 manager startapp app_name
  3. # 在总urls配置地址
  4. from django.conf.urls import include
  5. urlpatterns = [
  6. path('file/', include('app_name.urls'))
  7. ]
  8. # 在app_name app 下,配置url
  9. from . import views
  10. urlpatterns = [
  11. path('upload/', views.upload_file, name='upload'),
  12. path('download/', views.download_file, name='download'),
  13. ]

编写views

  1. from django.views.decorators.csrf import csrf_exempt
  2. from django.views.decorators.http import require_http_methods
  3. from django.http import StreamingHttpResponse
  4. def handle_uploaded_file(f):
  5. # 文件被上传到path 地址 上
  6. name = f.name
  7. with open(path, 'wb') as destination:
  8. for hunk in f.chunks():
  9. destination.write(chunk)
  10. @csrf_except
  11. @require_http_methods(['POST'])
  12. def upolad_file(request):
  13. # django 前端通过 form-data file 上传文件,文件存在request.FILES中
  14. # 可以在form中配置文件上传类型,下面会编写form
  15. form = UploadFileForm(request.FILES)
  16. if form.is_valid():
  17. handle_uploaded_file(request.FILES['file'])
  18. return JsonResponse({'status': 'success', 'code': 200})
  19. else:
  20. return JsonResponse(form.errors)
  21. def download_file(request):
  22. form = DownFileForm(request.GET)
  23. def file_iterator(file_name, chunk_siza=512):
  24. with open(file_name, 'rb') as f:
  25. while True:
  26. c = f.read(chunk_size)
  27. if c:
  28. yield c
  29. else:
  30. break
  31. if form.is_valid():
  32. file_name = os.path.join(seetting.DOWNLOAD_ROOT, form.clean_data['file_name'])
  33. response = StreamingHttpResponse(file_iterator(file_name))
  34. response['Content-Type'] = 'application/octet-stream'
  35. response['Content-Disposition'] = 'attachment; filename="{}"'.format(file_name)
  36. return response
  37. else:
  38. return JsonResponse(form.errors)

编写form

  1. from django import forms
  2. class UploadFileForm(forms.Form):
  3. file = forms.FileField()
  4. def clean_file(self):
  5. file = self.cleaned_data['file']
  6. ext = file.name.split('.')[-1].lower()
  7. if ext not in ['xls', 'xlsx']:
  8. raise forms.ValidationError("只能上传excel文件")
  9. return file

总结:

还是要看文档,web 简单来说就是请求,响应,平时还是要多写