【问题标题】:Django removes "@" and other special character from file nameDjango 从文件名中删除“@”和其他特殊字符
【发布时间】:2021-01-05 02:46:35
【问题描述】:

我想上传一个文件名作为上传者电子邮件的文件。我知道这不是操作系统文件系统问题,也不是不支持的 python 操作,因为我确实在 python 中保存了这种格式的图像。现在我想将图像保存在模型中(特别是 ImageField)。

如果存在一些具有相同名称的现有图像,我正在使用 OverwriteStorage 覆盖图像。

保存图片

model = Model.objects.create(email=email)
# Blob to image
tempfile_io = io.BytesIO()
img.save(tempfile_io, 'JPEG')
image_file = InMemoryUploadedFile(tempfile_io, None, email + ".jpeg",'image/jpeg',tempfile_io.getbuffer().nbytes, None)
print("email is", email)
model.pic.save(email + ".jpg",image_file)

型号

class Model(models.Model):
    email = models.EmailField()
    pic = models.ImageField(upload_to="pics", storage=OverwriteStorage())

覆盖存储

class OverwriteStorage(FileSystemStorage):
    def get_available_name(self, name, *args, **kwargs):
        print("name is", name)
        if self.exists(name):
            self.delete(name)
        return name

但由于某种原因,我在 OverwriteStorage-get_available_name 中没有得到确切的名称。

email is xyz@example.com
name is xyzexamle.com.jpg

注意@符号是如何被粗暴地删除的。 是否有任何文件名字符串检查我需要禁用。如何让 Django 使用给定的确切文件名(尽可能)?

【问题讨论】:

    标签: django django-models imagefield


    【解决方案1】:

    您必须将get_valid_name(name) 覆盖为documented

    get_valid_name(name)

    返回适合与底层存储一起使用的文件名 系统。传递给此方法的名称参数是原始的 发送到服务器的文件名,或者,如果 upload_to 是可调用的,则 在任何路径信息之后由该方法返回的文件名 删除。覆盖它以自定义非标准字符的方式 转换为安全的文件名。

    来自source

    def get_valid_name(self, name):
        """
        Return a filename, based on the provided filename, that's suitable for
        use in the target storage system.
        """
        return get_valid_filename(name)
    

    【讨论】:

      猜你喜欢
      • 2016-02-04
      • 1970-01-01
      • 2016-10-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-10-17
      相关资源
      最近更新 更多