【Django Admin】在线查看与下载文件配置

models.py的配置

# user是存放在media里面的指定路径文件夹下的,file是给这个字段存放的文件夹的
file = models.FileField(upload_to="user/file",verbose_name="下载资料",blank=True,null=True)

technology_images = fields.ImageField(verbose_name='在线查看图片',max_length=128,help_text='目前仅支持上传png,jpg,jpeg图片格式', accept=".png,.jpg,.jpeg",null=True,blank=True,) 
# 必须使用上 这个依赖库
# django-cleanup :                                     
# 用于删除替换不需要的media文件                      
# 安装后配置:                      
# INSTALLED_APPS =
# [         
# 	  ...        
# 'django_cleanup.apps.CleanupConfig', # 要放在最后一个                      
# ]

Urls.py的配置

from .settings import MEDIA_ROOT

from django.views.static import serve  # 上传文件处理函数
# 下载文件
url("media/user/(?P<path>.*)$", down.FileDown.as_view()),   # 下载函数在下面
# 在线查看文件
url(r'^media/(?P<path>.*)$', serve, {"document_root": MEDIA_ROOT}), 

3:下载函数文件

""" 下载文件 """
from django.utils.http import urlquote
from rest_framework.views import APIView
from django.http import FileResponse
import os
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))


class FileDown(APIView):
    def get(self, request,path):
        path,name = str(path).split("-") # 这里的NAME就是上面传入的值
        path = BASE_DIR + "/media/user/" + path
        file_name = name + "." +  path.split(".")[-1]
        file = open(path.replace(" ",""), 'rb')
        response = FileResponse(file)
        response['Content-Type'] = 'application/octet-stream'
        response['Content-Disposition'] = "attachment;filename={}".format(urlquote(file_name))  # 设置名字
        return response
posted @ 2022-09-28 17:16  PythonNew_Mr.Wang  Views(287)  Comments(0)    收藏  举报