gpt4 book ai didi

django - 服务器端只接受FileField中的某种文件类型

转载 作者:行者123 更新时间:2023-11-28 19:33:34 24 4
gpt4 key购买 nike

如何在服务器端优雅地限制 FileField 只接受某种类型的文件(视频、音频、pdf 等)?

最佳答案

一种非常简单的方法是使用自定义验证器。

在您应用的 validators.py 中:

def validate_file_extension(value):
import os
from django.core.exceptions import ValidationError
ext = os.path.splitext(value.name)[1] # [0] returns path+filename
valid_extensions = ['.pdf', '.doc', '.docx', '.jpg', '.png', '.xlsx', '.xls']
if not ext.lower() in valid_extensions:
raise ValidationError('Unsupported file extension.')

然后在您的 models.py 中:

from .validators import validate_file_extension

...并为您的表单字段使用验证器:

class Document(models.Model):
file = models.FileField(upload_to="documents/%Y/%m/%d", validators=[validate_file_extension])

另请参阅:How to limit file types on file uploads for ModelForms with FileFields? .

Warning

For securing your code execution environment from malicious media files

  1. Use Exif libraries to properly validate the media files.
  2. Separate your media files from your application codeexecution environment
  3. If possible use solutions like S3, GCS, Minio oranything similar
  4. When loading media files on client side, use client native methods (for example if you are loading the media files non securely in abrowser, it may cause execution of "crafted" JavaScript code)

关于django - 服务器端只接受FileField中的某种文件类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3648421/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com