经验首页 前端设计 程序设计 Java相关 移动开发 数据库/运维 软件/图像 大数据/云计算 其他经验
当前位置:技术经验 » 程序设计 » Django » 查看文章
Django实现文件分享系统的完整代码
来源:jb51  时间:2021/5/7 9:36:36  对本文有异议

一、效果展示

文件上传和展示:

upload

image-20210506205404410

文件搜索:

search

文件下载:

download

删除文件:

delete

二、关键代码

#urls.py

  1. from django.urls import path,re_path
  2. from .views import HomeView,DisplayView,MyView,SearchView
  3. from . import views
  4.  
  5. app_name = 'share'
  6. urlpatterns = [
  7. path('', HomeView.as_view(), name='home'),
  8. # 当用户发起主页的GET请求时
  9. # 会调用 HomeView的父类的get方法处理
  10. # 怎么调用呢,这里需要用到HomeView的父类的as_view方法
  11. # 此方法会调用dispatch方法, 由后者根据请求类型选择响应的处理函数
  12. path('s/<code>', DisplayView.as_view(), name='display'), #展示上传成功的文件
  13. path('my/', MyView.as_view(), name='my'), #管理文件
  14. path('search/', SearchView.as_view(), name='search'), #搜索文件
  15. re_path(r'^download/(?P<id>\d*$)', views.Download, name='download'), #下载文件
  16. re_path(r'^delete/(?P<id>\d*$)', views.DeleteFile, name='delete'), #删除文件
  17.  
  18. ]

#views.py

  1. from django.shortcuts import render
  2. from django.views.generic import TemplateView,ListView
  3. import random
  4. import string
  5. import json
  6. from django.http import HttpResponse,HttpResponsePermanentRedirect,StreamingHttpResponse,HttpResponseRedirect
  7. from .models import Upload
  8. import os
  9. # 创建视图类需要基础视图基类
  10. # 例如 TemplateView 就是用于展示页面的模板视图基类
  11. # 该类仅提供get方法,用于处理GET请求
  12. # 当然也可以自定义其他方法,例如post
  13. # 展示主页的话,只需要提供模板文件的名字即可
  14. # 当客户端发起get请求时,由父类的get方法处理请求
  15. # 该属性用于提供模板文件,在父类的方法中被调用
  16. class HomeView(TemplateView):
  17. '''用来展示主页的视图类
  18. '''
  19. template_name = "base.html"
  20. def post(self, request):
  21. if request.FILES: #如果表单中有文件
  22. file = request.FILES.get('file')
  23. code = ''.join(random.sample(string.digits, 8)) #设置文件的唯一标识code,并且用作文件改名
  24. name = file.name
  25. size = int(file.size)
  26. path = 'filesystem/static/file/' + code + name #设置文件保存的路径,并且更改文件名(防止重名文件)
  27. with open(path, 'wb') as f:
  28. f.write(file.read()) #保存文件
  29.  
  30. upload = Upload(
  31. path = path,
  32. name = name,
  33. filesize = size,
  34. code = code,
  35. pcip = str(request.META['REMOTE_ADDR'])
  36. )
  37. upload.save() #向数据库插入数据
  38. return HttpResponsePermanentRedirect("/share/s/"+code) #重定向到DisplayView
  39.  
  40. class DisplayView(ListView):
  41. '''展示文件的视图类
  42. '''
  43. def get(self, request, code):
  44. uploads = Upload.objects.filter(code=code) #显示出指定文件
  45. if uploads:
  46. for upload in uploads:
  47. upload.dowmloadcount += 1 #记录访问次数
  48. upload.save()
  49. return render(request, 'content.html', {'content':uploads, 'host':request.get_host()})
  50.  
  51. class MyView(ListView):
  52. '''
  53. 用户管理视图类,就是用户管理文件的那个页面的视图类
  54. '''
  55. def get(self, request):
  56. #ip = request.META['REMOTE_ADDR']
  57. #uploads = Upload.objects.filter(pcip=ip)
  58. uploads = Upload.objects.all() #查询所有文件
  59. for upload in uploads:
  60. upload.dowmloadcount += 1
  61. upload.save()
  62. return render(request, 'content.html', {'content':uploads}) #将所有文件信息渲染展示
  63.  
  64. class SearchView(ListView):
  65. '''搜索功能的视图类
  66. '''
  67. def get(self, request):
  68. code = request.GET.get('kw') # 获取关键词
  69. u = Upload.objects.filter(name__icontains=str(code)) # 模糊搜索
  70. # select * from share_upload where name like '%code%';
  71. data = {}
  72. if u:
  73. # 将符合条件的数据放到data中
  74. for i in range(len(u)): # 循环输出查询的结果
  75. u[i].dowmloadcount += 1
  76. u[i].save()
  77. data[i]={}
  78. data[i]['download'] = u[i].dowmloadcount
  79. data[i]['filename'] = u[i].name
  80. data[i]['id'] = u[i].id
  81. data[i]['ip'] = str(u[i].pcip)
  82. data[i]['size'] = u[i].filesize
  83. data[i]['time'] = str(u[i].datetime.strftime('%Y-%m-%d %H:%M'))
  84.  
  85. return HttpResponse(json.dumps(data), content_type="application/json")
  86.  
  87.  
  88. def Download(request, id):
  89. """
  90. 下载压缩文件
  91. :param request:
  92. :param id: 数据库id
  93. :return:
  94. """
  95. data = Upload.objects.all()
  96. file_name = "" # 文件名
  97. for i in data:
  98. if i.code == id: # 判断id一致时
  99. file_name = i.name # 覆盖变量
  100.  
  101. base_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # 项目根目录
  102. file_path = os.path.join(base_dir, 'filesystem', 'static', 'file', file_name) # 下载文件的绝对路径
  103.  
  104. if not os.path.isfile(file_path): # 判断下载文件是否存在
  105. return HttpResponse("Sorry but Not Found the File")
  106.  
  107. def file_iterator(file_path, chunk_size=512):
  108. """
  109. 文件生成器,防止文件过大,导致内存溢出
  110. :param file_path: 文件绝对路径
  111. :param chunk_size: 块大小
  112. :return: 生成器
  113. """
  114. with open(file_path, mode='rb') as f:
  115. while True:
  116. c = f.read(chunk_size)
  117. if c:
  118. yield c
  119. else:
  120. break
  121.  
  122. try:
  123. # 设置响应头
  124. # StreamingHttpResponse将文件内容进行流式传输,数据量大可以用这个方法
  125. response = StreamingHttpResponse(file_iterator(file_path))
  126. # 以流的形式下载文件,这样可以实现任意格式的文件下载
  127. response['Content-Type'] = 'application/octet-stream'
  128. # Content-Disposition就是当用户想把请求所得的内容存为一个文件的时候提供一个默认的文件名
  129. response['Content-Disposition'] = 'attachment;filename="{}"'.format(file_name)
  130. except:
  131. return HttpResponse("Sorry but Not Found the File")
  132. return response
  133.  
  134. def DeleteFile(request, id):
  135. '''删除指定文件'''
  136. data = Upload.objects.all()
  137. file_name = "" # 文件名
  138. for i in data:
  139. if i.code == id: # 判断id一致时
  140. file_name = i.code + i.name # 覆盖变量
  141.  
  142. base_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # 项目根目录
  143. file_path = os.path.join(base_dir, 'filesystem', 'static', 'file', file_name) # 下载文件的绝对路径
  144. if os.path.exists(file_path):
  145. os.remove(file_path)
  146. file = Upload.objects.get(code=id)
  147. file.delete()
  148. return HttpResponseRedirect('/share/my/')
  149.  
  150. '''
  151. except Exception as e:
  152. return http.HttpResponseForbidden('文件不存在,下载失败!')
  153. '''

到此这篇关于Django实现文件分享系统的完整代码的文章就介绍到这了,更多相关Django文件分享系统内容请搜索w3xue以前的文章或继续浏览下面的相关文章希望大家以后多多支持w3xue!

 友情链接:直通硅谷  点职佳  北美留学生论坛

本站QQ群:前端 618073944 | Java 606181507 | Python 626812652 | C/C++ 612253063 | 微信 634508462 | 苹果 692586424 | C#/.net 182808419 | PHP 305140648 | 运维 608723728

W3xue 的所有内容仅供测试,对任何法律问题及风险不承担任何责任。通过使用本站内容随之而来的风险与本站无关。
关于我们  |  意见建议  |  捐助我们  |  报错有奖  |  广告合作、友情链接(目前9元/月)请联系QQ:27243702 沸活量
皖ICP备17017327号-2 皖公网安备34020702000426号