如何使用django-filebrowser重命名文件,然后再将其上传到文件夹

时间:2012-04-10 02:27:58

标签: django upload django-filebrowser

喜欢django的upload_to

def upload_to(instance, filename):
    filename = time.strftime('%Y%m%d%H%M%S')
    ym = time.strftime('%Y%m')
    return 'uploads/%s/%s.jpg' % (ym,filename)

class Person(models.Model):
    first_name = models.CharField(max_length=30)
    last_name = models.CharField(max_length=30)
    photo = models.ImageField(u"Image (Upload)",upload_to=upload_to)

文件保存'上传/%s /%s.jpg'

但改为

photo = FileBrowseField("Image", max_length=200, directory="uploads/", extensions=[".jpg"], blank=True, null=True)

如何在将文件上传到文件夹之前重命名文件 像django的upload_to

1 个答案:

答案 0 :(得分:1)

在filebrowser / sites.py中,您可以在上传/处理上传时为此创建一个钩子:

def _upload_file(self, request):
    """
    Upload file to the server.
    """
    if request.method == "POST":
        folder = request.GET.get('folder', '')

        if len(request.FILES) == 0:
            return HttpResponseBadRequest('Invalid request! No files included.')
        if len(request.FILES) > 1:
            return HttpResponseBadRequest('Invalid request! Multiple files included.')

        filedata = list(request.FILES.values())[0]

        fb_uploadurl_re = re.compile(r'^.*(%s)' % reverse("filebrowser:fb_upload", current_app=self.name))
        folder = fb_uploadurl_re.sub('', folder)

        path = os.path.join(self.directory, folder)
        # we convert the filename before uploading in order
        # to check for existing files/folders
        file_name = convert_filename(filedata.name)
        filedata.name = file_name
        file_path = os.path.join(path, file_name
        ....

您可以在此处将file_path修改为您喜欢的任何内容,或修改文件名。

对于那些只想确保文件不被覆盖的人,可以在settings.py中设置FILEBROWSER_OVERWRITE_EXISTING标志:

FILEBROWSER_OVERWRITE_EXISTING = False

这将确保您在编辑文件时为它们指定一个唯一的名称,并确保新上传文件的文件名转换为独特的文件浏览器在filebrowser / utils.py中定义的convert_filename方法

有关filebrowser设置的更多信息here。希望这会有所帮助:)