我有一个FileField
的模型,用于保存用户上传的文件。由于我想节省空间,我想避免重复。
我想要实现的目标:
1 且 2 已经有效,但我将如何忘记上传的副本并改用现有文件?
请注意,我想保留现有文件而不覆盖它(主要是为了保持修改时间不变 - 更适合备份)。
备注:
django.core.files.uploadhandler.TemporaryFileUploadHandler
代码:
def media_file_name(instance, filename):
h = instance.md5sum
basename, ext = os.path.splitext(filename)
return os.path.join('mediafiles', h[0:1], h[1:2], h + ext.lower())
class Media(models.Model):
orig_file = models.FileField(upload_to=media_file_name)
md5sum = models.CharField(max_length=36)
...
def save(self, *args, **kwargs):
if not self.pk: # file is new
md5 = hashlib.md5()
for chunk in self.orig_file.chunks():
md5.update(chunk)
self.md5sum = md5.hexdigest()
super(Media, self).save(*args, **kwargs)
感谢任何帮助!
答案 0 :(得分:27)
感谢alTus的回答,我能够发现写 custom storage class 是关键,而且比预期的要容易。
_save
方法来编写文件(如果文件已经存在),我只返回名称。get_available_name
,以避免在已存在同名文件的情况下将数字附加到文件名我不知道这是否是正确的方式,但到目前为止工作正常。
希望这很有用!
以下是完整的示例代码:
import hashlib
import os
from django.core.files.storage import FileSystemStorage
from django.db import models
class MediaFileSystemStorage(FileSystemStorage):
def get_available_name(self, name, max_length=None):
if max_length and len(name) > max_length:
raise(Exception("name's length is greater than max_length"))
return name
def _save(self, name, content):
if self.exists(name):
# if the file exists, do not call the superclasses _save method
return name
# if the file is new, DO call it
return super(MediaFileSystemStorage, self)._save(name, content)
def media_file_name(instance, filename):
h = instance.md5sum
basename, ext = os.path.splitext(filename)
return os.path.join('mediafiles', h[0:1], h[1:2], h + ext.lower())
class Media(models.Model):
# use the custom storage class fo the FileField
orig_file = models.FileField(
upload_to=media_file_name, storage=MediaFileSystemStorage())
md5sum = models.CharField(max_length=36)
# ...
def save(self, *args, **kwargs):
if not self.pk: # file is new
md5 = hashlib.md5()
for chunk in self.orig_file.chunks():
md5.update(chunk)
self.md5sum = md5.hexdigest()
super(Media, self).save(*args, **kwargs)
答案 1 :(得分:7)
AFAIK你无法使用保存/删除方法轻松实现这一点.coz文件的处理非常具体。
但是你可以尝试那样的smth。
首先,我的简单md5文件哈希函数:
def md5_for_file(chunks):
md5 = hashlib.md5()
for data in chunks:
md5.update(data)
return md5.hexdigest()
下一个simple_upload_to
就像你的media_file_name函数一样。
你应该这样使用它:
def simple_upload_to(field_name, path='files'):
def upload_to(instance, filename):
name = md5_for_file(getattr(instance, field_name).chunks())
dot_pos = filename.rfind('.')
ext = filename[dot_pos:][:10].lower() if dot_pos > -1 else '.unknown'
name += ext
return os.path.join(path, name[:2], name)
return upload_to
class Media(models.Model):
# see info about storage below
orig_file = models.FileField(upload_to=simple_upload_to('orig_file'), storage=MyCustomStorage())
当然,这仅仅是一个例子,因此路径生成逻辑可能是多种多样的。
最重要的部分:
from django.core.files.storage import FileSystemStorage
class MyCustomStorage(FileSystemStorage):
def get_available_name(self, name):
return name
def _save(self, name, content):
if self.exists(name):
self.delete(name)
return super(MyCustomStorage, self)._save(name, content)
如您所见,此自定义存储会在保存之前删除文件,然后保存具有相同名称的新文件。 所以在这里你可以实现你的逻辑,如果不删除(并因此更新)文件很重要。
有关存储空间的更多信息,请访问:https://docs.djangoproject.com/en/1.5/ref/files/storage/
答案 2 :(得分:2)
我有同样的问题,发现了这个问题。因为这并不常见,所以我在网上搜索并找到了以下Python软件包,这些软件包可以完全按照您的要求进行操作:
https://pypi.python.org/pypi/django-hashedfilenamestorage
如果SHA1哈希是不可能的,我认为添加MD5哈希支持的拉取请求将是一个好主意。
答案 3 :(得分:0)
如果上传的文件已经存在,这个答案帮助我解决了我想提出异常的问题。如果上传位置中已存在具有相同名称的文件,则此版本会引发异常。
from django.core.files.storage import FileSystemStorage
class FailOnDuplicateFileSystemStorage(FileSystemStorage):
def get_available_name(self, name):
return name
def _save(self, name, content):
if self.exists(name):
raise ValidationError('File already exists: %s' % name)
return super(
FailOnDuplicateFileSystemStorage, self)._save(name, content)
答案 4 :(得分:0)
数据来自模板->表单->视图-> db(model)。尽早停止重复是有意义的。在这种情况下,forms.py。
# scripts.py
import hashlib
from .models import *
def generate_sha(file):
sha = hashlib.sha1()
file.seek(0)
while True:
buf = file.read(104857600)
if not buf:
break
sha.update(buf)
sha1 = sha.hexdigest()
file.seek(0)
return sha1
# models.py
class images(models.Model):
label = models.CharField(max_length=21, blank=False, null=False)
image = models.ImageField(upload_to='images/')
image_sha1 = models.CharField(max_length=40, blank=False, null=False)
create_time = models.DateTimeField(auto_now=True)
# forms.py
class imageForm(forms.Form):
Label = forms.CharField(max_length=21, required=True)
Image = forms.ImageField(required=True)
def clean(self):
cleaned_data = super(imageForm, self).clean()
Label = cleaned_data.get('Label')
Image = cleaned_data.get('Image')
sha1 = generate_sha(Image)
if images.objects.filter(image_sha1=sha1).exists():
raise forms.ValidationError('This already exists')
if not Label:
raise forms.ValidationError('No Label')
if not Image:
raise forms.ValidationError('No Image')
# views.py
from .scripts import *
from .models import *
from .forms import *
def image(request):
if request.method == 'POST':
form = imageForm(request.POST, request.FILES)
if form.is_valid():
photo = images (
payee=request.user,
image=request.FILES['Image'],
image_sha1=generate_sha(request.FILES['Image'],),
label=form.cleaned_data.get('Label'),
)
photo.save()
return render(request, 'stars/image_form.html', {'form' : form})
else:
form = imageForm()
context = {'form': form,}
return render(request, 'stars/image_form.html', context)
# image_form.html
{% extends "base.html" %}
{% load static %}
{% load staticfiles %}
{% block content %}
<div class="card mx-auto shadow p-3 mb-5 bg-white rounded text-left" style="max-width: 50rem;">
<div class="container">
<form action="{% url 'wallet' %}" method="post" enctype="multipart/form-data">
{% csrf_token %}
{{ form }}
<input type="submit" value="Upload" class="btn btn-outlined-primary">
</form>
{% if form.errors %}
{% for field in form %}
{% for error in field.errors %}
<p> {{ error }} </p>
{% endfor %}
{% endfor %}
{% endif %}
</div>
</div>
{% endblock content %}
参考:http://josephmosby.com/2015/05/13/preventing-file-dupes-in-django.html