python

一。 settings.py

MEDIA_URL = "/qir/"  # 设置获取文件时的访问根路径

MEDIA_ROOT = os.path.join(BASE_DIR, "FileRoot")     # 设置文件存储在项目的根路径(MEDIA_ROOT 是固定值,不可更改)

二。 models.py

class MyFiles(models.Model):
    my_files_path = PathAndRename("my_files")    # 该表的文件存储路径
file = models.FileField(verbose_name="文件", null=True)

三。 自定义一个创建表文件夹的类

from django.utils.deconstruct import deconstructible
from django.utils import timezone
from django.conf import settings

import os


@deconstructible
class PathAndRename(object):

    def __init__(self, sub_path):
        self.path = sub_path    # 要创建的文件夹名称

        self.full_path = "%s/%s" % (settings.MEDIA_ROOT, sub_path)  # 拼接 settings 中设置的根目录
        if not os.path.exists(self.full_path):  # 拼接的路径是否被创建
            os.makedirs(self.full_path)

    def __call__(self, instance, filename):
        ext = filename.split('.')[-1]
        t = timezone.now().strftime('%Y%m%d%H%M%S%f')

        if instance.pk:
            filename = '{}-{}.{}'.format(instance.pk, t, ext)
        else:
            filename = '{}.{}'.format(t, ext)
        return os.path.join(self.path , filename)

四。 自定义一个保存文件的方法。

def save_image(files, path, user=None):
    if user:    # 是否使用用户id作为文件存储路径
        file_name = "%s/%s" % (path, user.id)   
        if not os.path.exists(settings.MEDIA_ROOT+"/"+file_name):   # 没有该路径则创建
            os.makedirs(settings.MEDIA_ROOT+"/"+file_name)
        file_name = file_name+"/%s.%s" % (datetime.datetime.now().strftime("%Y%m%d%H%M%S%f"), files.name.split(".")[-1])
    else:
        file_name = "%s/%s.%s" % (path, datetime.datetime.now().strftime("%Y%m%d%H%M%S%f"), files.name.split(".")[-1])
    full_name = "%s/%s" % (settings.MEDIA_ROOT, file_name)
    with open(full_name, "wb+") as f:   # 将文件存储到项目中
        for chunk in files.chunks():
            f.write(chunk)
    return file_name, full_name

五。 views.py ( 获取文件并存储 )

class FilesViews(APIView):
    def post(request, *args, **kwargs):
        file = request.FILES.get('file', None)
        file_name, full_name = save_image(file, MyFiles.my_files_path.path, request.user)
        MyFiles.objects.create(file=file_name)
        ...

六。 获取文件路径并返回前端。

class FilesViews(APIView):
    def get(request, *args, **kwargs):
        file_list = Myfiles.objects.all()    # 获取所有文件
        file_path_list = []
        for file_obj in file_list:    # 获取每个文件的存储路径
            file_path_list.append(file_obj.file.path)
        ...
                
原文地址:https://www.cnblogs.com/chaoqi/p/11920767.html