Django(音频)文件验证

发布于 2024-11-11 05:42:48 字数 145 浏览 2 评论 0原文

我正在试验一个允许用户上传音频文件的网站。我已经阅读了所有我能拿到的文档,但找不到太多关于验证文件的内容。

这里完全是新手(之前从未做过任何类型的文件验证)并试图弄清楚这一点。有人可以握住我的手并告诉我我需要知道什么吗?

一如既往,预先感谢您。

I'm experimenting with a site that will allow users to upload audio files. I've read every doc that I can get my hands on but can't find much about validating files.

Total newb here (never done any file validation of any kind before) and trying to figure this out. Can someone hold my hand and tell me what I need to know?

As always, thank you in advance.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

躲猫猫 2024-11-18 05:42:48

您希望在将文件写入磁盘之前对其进行验证。当您上传文件时,表单将被验证,然后上传的文件将被传递到处理程序/方法,该处理程序/方法处理对服务器上磁盘的实际写入。因此,在这两个操作之间,您想要执行一些自定义验证以确保它是有效的音频文件

您可以:

  • 检查文件是否小于特定大小(良好实践)
  • 然后检查提交的文件是否具有特定内容类型(即音频文件)
    • 这毫无用处,因为有人可以轻松欺骗它
  • 然后检查文件是否以某个扩展名(或多个扩展名)结尾
    • 这也没什么用
  • 尝试读取文件并查看它是否实际上是音频

(我还没有测试过这段代码)

models.py

class UserSong(models.Model):
    title = models.CharField(max_length=100)
    audio_file = models.FileField()

forms.py

class UserSongForm(forms.ModelForm):
     # Add some custom validation to our file field
     def clean_audio_file(self):
         file = self.cleaned_data.get('audio_file',False):
         if file:
             if file._size > 4*1024*1024:
                   raise ValidationError("Audio file too large ( > 4mb )")
             if not file.content-type in ["audio/mpeg","audio/..."]:
                   raise ValidationError("Content-Type is not mpeg")
             if not os.path.splitext(file.name)[1] in [".mp3",".wav" ...]:
                   raise ValidationError("Doesn't have proper extension")
             # Here we need to now to read the file and see if it's actually 
             # a valid audio file. I don't know what the best library is to 
             # to do this
             if not some_lib.is_audio(file.content):
                   raise ValidationError("Not a valid audio file")
             return file
         else:
             raise ValidationError("Couldn't read uploaded file")

views.py
from utils import handle_uploaded_file

def upload_file(request):
    if request.method == 'POST':
        form = UserSongForm(request.POST, request.FILES)
        if form.is_valid():
            # If we are here, the above file validation has completed
            # so we can now write the file to disk
            handle_uploaded_file(request.FILES['file'])
            return HttpResponseRedirect('/success/url/')
    else:
        form = UploadFileForm()
    return render_to_response('upload.html', {'form': form})

utils.py

# from django's docs
def handle_uploaded_file(f):
    ext = os.path.splitext(f.name)[1]
    destination = open('some/file/name%s'%(ext), 'wb+')
    for chunk in f.chunks():
        destination.write(chunk)
    destination.close()

https://docs.djangoproject.com/en/dev/topics/http/file-uploads/#file-uploads">https:// /docs.djangoproject.com/en/dev/topics/http/file-uploads/#file-uploads
https://docs.djangoproject.com/en/dev/ref/forms/fields/#filefield
https://docs.djangoproject.com/en/dev/ref /files/file/#django.core.files.File

You want to validate the file before it gets written to disk. When you upload a file, the form gets validated then the uploaded file gets passed to a handler/method that deals with the actual writing to the disk on your server. So in between these two operations, you want to perform some custom validation to make sure it's a valid audio file

You could:

  • check if the the file is less then a certain size (good practice)
  • then check if the submitted file has a certain content type (i.e. an audio file)
    • this is pretty useless as someone could easily spoof it
  • then check that the file ends in a certain extension (or extensions)
    • this is also pretty useless
  • try read the file and see if it's actually audio

(I haven't tested this code)

models.py

class UserSong(models.Model):
    title = models.CharField(max_length=100)
    audio_file = models.FileField()

forms.py

class UserSongForm(forms.ModelForm):
     # Add some custom validation to our file field
     def clean_audio_file(self):
         file = self.cleaned_data.get('audio_file',False):
         if file:
             if file._size > 4*1024*1024:
                   raise ValidationError("Audio file too large ( > 4mb )")
             if not file.content-type in ["audio/mpeg","audio/..."]:
                   raise ValidationError("Content-Type is not mpeg")
             if not os.path.splitext(file.name)[1] in [".mp3",".wav" ...]:
                   raise ValidationError("Doesn't have proper extension")
             # Here we need to now to read the file and see if it's actually 
             # a valid audio file. I don't know what the best library is to 
             # to do this
             if not some_lib.is_audio(file.content):
                   raise ValidationError("Not a valid audio file")
             return file
         else:
             raise ValidationError("Couldn't read uploaded file")

views.py
from utils import handle_uploaded_file

def upload_file(request):
    if request.method == 'POST':
        form = UserSongForm(request.POST, request.FILES)
        if form.is_valid():
            # If we are here, the above file validation has completed
            # so we can now write the file to disk
            handle_uploaded_file(request.FILES['file'])
            return HttpResponseRedirect('/success/url/')
    else:
        form = UploadFileForm()
    return render_to_response('upload.html', {'form': form})

utils.py

# from django's docs
def handle_uploaded_file(f):
    ext = os.path.splitext(f.name)[1]
    destination = open('some/file/name%s'%(ext), 'wb+')
    for chunk in f.chunks():
        destination.write(chunk)
    destination.close()

https://docs.djangoproject.com/en/dev/topics/http/file-uploads/#file-uploads
https://docs.djangoproject.com/en/dev/ref/forms/fields/#filefield
https://docs.djangoproject.com/en/dev/ref/files/file/#django.core.files.File

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文