通用路由: # 下载文件 url("media/(?P<path>.*)$", file_down.FileDown.as_view()) 通用下载文件函数: from django.utils.http import urlquote from rest_framework.views import APIView from django.shortcuts import render, redirect, HttpResponse from dal import models from django.http import JsonResponse, FileResponse, StreamingHttpResponse import os import xlwt BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # C:UsersuserDesktopDownTest class FileDown(APIView): def get(self, request,path): path = BASE_DIR + "\media\" + path.replace("/","\") print("path",path) message = {} file_name = path.split("\")[-1] print("file_name",file_name) file = open(path.replace(" ",""), 'rb') # 字符串替换成文件 # 告诉浏览器 这个是下载文件 response = FileResponse(file) response['Content-Type'] = 'application/octet-stream' response['Content-Disposition'] = "attachment;filename={}".format(urlquote(file_name)) # 设置名字 print(response) return response
通用settings配置: LANGUAGE_CODE = 'zh-hans' TIME_ZONE = 'Asia/Shanghai' USE_I18N = True USE_L10N = True USE_TZ = True # Internationalization # https://docs.djangoproject.com/en/1.11/topics/i18n/ STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static'), os.path.join(BASE_DIR, "media"), ] # Django用户上传的都叫media文件 MEDIA_URL = "/media/" # media配置,用户上传的文件都默认放在这个文件夹下 MEDIA_ROOT = os.path.join(BASE_DIR, "media") REST_FRAMEWORK = { "DEFAULT_AUTHENTICATION_CLASSES": [], "DEFAULT_PERMISSION_CLASSES": [], }
数据库设计: class Suggestion(models.Model): """ 项目建议表 """ name = models.ForeignKey(to="UserInfo",verbose_name="建议人员") file = models.FileField(upload_to='suggestion/files', null=False,unique=True, blank=False,verbose_name="文件(点击下载)") file_name = models.CharField( max_length=50, null=False,verbose_name="文件标题") is_staff =models.BooleanField(verbose_name="是否紧急") is_staf =models.BooleanField(verbose_name="是否采用") def __str__(self): return self.file class Meta: verbose_name = "项目建议表" verbose_name_plural = verbose_name db_table = 'Suggestion'