django之重写FileField字段的保存

重写FileField字段的保存,以重命名为例

settings.py添加配置

settings.py中末尾添加配置如下,指定指向的操作文件中的类:

# 文件上传重写
DEFAULT_FILE_STORAGE = "app.customfilefield.storage.FileStorage"

添加FileStorage

app应用下添加python包customfilefield,注意有init.py文件,customfilefield下创建py文件storage.py,文件内容为:

storage.py

# -*-coding:utf-8 -*-
from django.core.files.storage import FileSystemStorage
from django.http import HttpResponse from django.conf import settings import os, time, random from app import utils class FileStorage(FileSystemStorage): def __init__(self, location=settings.MEDIA_ROOT, base_url=settings.MEDIA_URL): #初始化 super(FileStorage, self).__init__(location, base_url) #重写 _save方法 def _save(self, name, content): #文件扩展名 ext = os.path.splitext(name)[1] #文件目录 d = os.path.dirname(name) # 定义文件名,源文件名,避开系统定义的随机字符串追加,所以避开不用name字段 end = utils.find_last(str(content), ".") filename = "" if end != -1: filename = str(content)[:end] # 定义文件名,年月日时分秒随机数 fn = time.strftime("%Y%m%d%H%M%S") fn = fn + "_%d" % random.randint(0,100) #重写合成文件名 name = os.path.join(d, filename + fn + ext) #调用父类方法 return super(FileStorage, self)._save(name, content) 

utils.py

# 获取字符串中指定字符最后一次出现的位置
def find_last(string,str): last_position=-1 while True: position=string.find(str,last_position+1) if position==-1: return last_position last_position=position

如此,最后上传的文件名为原文件名加上年月日时分秒加上0-100的随机数保存,效果如下:

猜你喜欢

转载自www.cnblogs.com/pcent/p/10831989.html