django之重寫FileField字段的保存

重寫FileField字段的保存,以重命名爲例python

settings.py添加配置

settings.py中末尾添加配置以下,指定指向的操做文件中的類:django

# 文件上傳重寫
DEFAULT_FILE_STORAGE = "app.customfilefield.storage.FileStorage"

添加FileStorage

app應用下添加python包customfilefield,注意有init.py文件,customfilefield下建立py文件storage.py,文件內容爲:app

storage.pydom

# -*-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.pyurl

# 獲取字符串中指定字符最後一次出現的位置
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的隨機數保存,效果以下:spa

clipboard.png

相關文章
相關標籤/搜索