ユーザーがオーディオ ファイルをアップロードできるサイトを試しています。手に入れることができるすべてのドキュメントを読みましたが、ファイルの検証についてはあまり見つかりません。
ここで完全な初心者(これまでにいかなる種類のファイル検証も行ったことがない)で、これを理解しようとしています。誰かが私の手を握って、私が知る必要があることを教えてもらえますか?
いつもありがとうございます。
ユーザーがオーディオ ファイルをアップロードできるサイトを試しています。手に入れることができるすべてのドキュメントを読みましたが、ファイルの検証についてはあまり見つかりません。
ここで完全な初心者(これまでにいかなる種類のファイル検証も行ったことがない)で、これを理解しようとしています。誰かが私の手を握って、私が知る必要があることを教えてもらえますか?
いつもありがとうございます。
ファイルがディスクに書き込まれる前に検証したいとします。ファイルをアップロードすると、フォームが検証され、アップロードされたファイルが、サーバー上のディスクへの実際の書き込みを処理するハンドラー/メソッドに渡されます。したがって、これら 2 つの操作の間に、カスタム検証を実行して、有効なオーディオ ファイルであることを確認する必要があります。
あなたは出来る:
(私はこのコードをテストしていません)
models.py
class UserSong(models.Model):
title = models.CharField(max_length=100)
audio_file = models.FileField()
フォーム.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")
utils import handle_uploaded_file からのviews.py
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})
ユーティリティ.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