加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

【django】 后台上传于下载 (通用型下载文件的 路由与下载函数)

发布时间:2020-12-15 17:09:04 所属栏目:大数据 来源:网络整理
导读:通用路由: # 下载文件 url( " media/(?Ppath.*)$ " ,file_down.FileDown.as_view()) 通用下载文件函数: from django.utils.http import urlquote rest_framework.views import APIView django.shortcuts import render,redirect,HttpResponse dal import mo
通用路由:
     # 下载文件
    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:UsersuserDesktopDownTest


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配置,用户上传的文件都默认放在这个文件夹下
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'

?

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读