前端上传文件到后端

前端

  1. <form action="../uploadFile" method="post" enctype="multipart/form-data" style=" display: block;width: 100%; height: 20%;">
  2. <input type="file" name="file" id="file" ><br>
  3. <input type="submit" value="导入文件" class="btn btn-primary" style="display: block;height: 40%;">
  4. </form>

后端

  1. @csrf_exempt
  2. def uploadFile(request):
  3. if request.method == 'POST':
  4. file_obj = request.FILES.get('file', None)
  5. print(file_obj.name)
  6. print(file_obj.size)
  7. with open('/Users/user3/PycharmProjects/djangoProject2/djangoProject2/' + file_obj.name, 'wb') as f:
  8. for line in file_obj.chunks():
  9. f.write(line)
  10. f.close()

前端点击下载后端文件

  1. @csrf_exempt
  2. def file_down(request):
  3. """
  4. 下载压缩文件
  5. :param request:
  6. :param id: 数据库id
  7. :return:
  8. """
  9. file_name = "result.xlsx"
  10. base_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # 项目根目录
  11. file_path = os.path.join(base_dir, 'upload', file_name) # 下载文件的绝对路径
  12. if not os.path.isfile(file_path): # 判断下载文件是否存在
  13. return HttpResponse("Sorry but Not Found the File")
  14. def file_iterator(file_path, chunk_size=512):
  15. """
  16. 文件生成器,防止文件过大,导致内存溢出
  17. :param file_path: 文件绝对路径
  18. :param chunk_size: 块大小
  19. :return: 生成器
  20. """
  21. with open(file_path, mode='rb') as f:
  22. while True:
  23. c = f.read(chunk_size)
  24. if c:
  25. yield c
  26. else:
  27. break
  28. try:
  29. # 设置响应头
  30. # StreamingHttpResponse将文件内容进行流式传输,数据量大可以用这个方法
  31. response = StreamingHttpResponse(file_iterator(file_path))
  32. # 以流的形式下载文件,这样可以实现任意格式的文件下载
  33. response['Content-Type'] = 'application/octet-stream'
  34. # Content-Disposition就是当用户想把请求所得的内容存为一个文件的时候提供一个默认的文件名
  35. response['Content-Disposition'] = 'attachment;filename="{}"'.format(file_name)
  36. except:
  37. return HttpResponse("Sorry but Not Found the File")
  38. return response

url

  1. re_path('download', views.file_down, name="download")

ui

  1. <a href="/download/">下载图片</a>