【django 】后台在线查看文件,下载文件的配置


# 下载


    # 下载文件
    url("media/(?P.*)$", 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 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",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
# 在线看
from .settings import MEDIA_ROOT
from django.views.static import serve  # 上传文件处理函数
url(r'^media/(?P.*)$', serve, {"document_root":MEDIA_ROOT})