通用路由: # 下载文件 url("media/(?P<path>.*)$",file_down.FileDown.as_view()) 通用下载文件函数: from django.utils.http import urlquote rest_framework.views import APIView django.shortcuts import render,redirect,HttpResponse dal import models django.http import JsonResponse,FileResponse,StreamingHttpResponse import os import xlwt BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # C:\Users\user\Desktop\DownTest class FileDown(APIView): def get(self,request,path): path = BASE_DIR + \\media\\" + path.replace(/",\\) print(path {} file_name = path.split(")[-1] print(file_name" ""),1)">'rb') # 字符串替换成文件 # 告诉浏览器 这个是下载文件 response = FileResponse(file) response[Content-Type'] = application/octet-stream response[Content-Dispositionattachment;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,1)">media用户上传的都叫media文件 MEDIA_URL = /media/ # media配置,用户上传的文件都默认放在这个文件夹下 MEDIA_ROOT = os.path.join(BASE_DIR,1)">) REST_FRAMEWORK = { DEFAULT_AUTHENTICATION_CLASSES: [],1)">DEFAULT_PERMISSION_CLASSES数据库设计: Suggestion(models.Model): """ 项目建议表 """ name = models.ForeignKey(to=UserInfo建议人员) file = models.FileField(upload_to=suggestion/files',null=False,unique=True,blank=False,1)">文件(点击下载)) file_name = models.CharField( max_length=50,1)">文件标题) is_staff =models.BooleanField(verbose_name=是否紧急) is_staf =models.BooleanField(verbose_name=是否采用) def __str__(self): return self.file Meta: verbose_name = 项目建议表 verbose_name_plural = verbose_name db_table = Suggestion'