[Django] Background upload and download (universal download file routing and download function)

General routing:
     # download file
    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 them

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 ' ) # Replace the string with a file

        # Tell the browser that this is a download file
        response = FileResponse(file)
        response['Content-Type'] = 'application/octet-stream'
        response['Content-Disposition'] = "attachment;filename={}".format(urlquote(file_name))  # 设置名字
        print(response)
        return response
General settings configuration: 
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 users upload media files
MEDIA_URL = "/media/"
# media configuration, all files uploaded by users are placed in this folder by default
MEDIA_ROOT = os.path.join(BASE_DIR, "media")


REST_FRAMEWORK = {
    "DEFAULT_AUTHENTICATION_CLASSES": [],
    "DEFAULT_PERMISSION_CLASSES": [],
}
Database design:
 class Suggestion (models.Model):
     "" "
     Project proposal form
    """
    name = models.ForeignKey(to="UserInfo",verbose_name="建议人员")
    file = models.FileField (upload_to = ' suggestion / files ' , null = False, unique = True, blank = False, verbose_name = " file (click to download) " )
    file_name = models.CharField (max_length = 50, null = False, verbose_name = " file title " )
    is_staff = models.BooleanField (verbose_name = "Is it urgent " )
    is_staf = models.BooleanField (verbose_name = " Whether to use " )

    def __str__(self):
        return self.file

    class Meta:
        verbose_name = " Project suggestion table " 
        verbose_name_plural = verbose_name
        db_table = 'Suggestion'

 

Guess you like

Origin www.cnblogs.com/wanghong1994/p/12716469.html