我一直在问这个问题很多recently。
我创建了上传表单
models.py
from django.db import models
from app.extra import ContentTypeRestrictedFileField
class upload(models.Model):
""" upload """
name = models.CharField(max_length=100)
description = models.CharField(max_length=250)
file = ContentTypeRestrictedFileField(
upload_to='/media/videos,'
content_types=['video/avi', 'video/mp4', 'video/3gp', 'video/wmp', 'video/flv', 'video/mov'],
max_upload_size=104857600
)
created = models.DateTimeField('created', auto_now_add=True)
modified = models.DateTimeField('modified', auto_now=True)
def __unicode__(self):
return self.name
form.py
from django.db.models import FileField
from django.forms import forms
from django.template.defaultfilters import filesizeformat
from django.utils.translation import ugettext_lazy as _
class ContentTypeRestrictedFileField(FileField):
"""
Same as FileField, but you can specify:
* content_types - list containing allowed content_types. Example: ['application/pdf', 'image/jpeg']
* max_upload_size - a number indicating the maximum file size allowed for upload.
2.5MB - 2621440
5MB - 5242880
10MB - 10485760
20MB - 20971520
50MB - 5242880
100MB 104857600
250MB - 214958080
500MB - 429916160
"""
def __init__(self, content_types=None,max_upload_size=104857600, **kwargs):
self.content_types = kwargs.pop('video/avi', 'video/mp4', 'video/3gp', 'video/wmp', 'video/flv', 'video/mov')
self.max_upload_size = max_upload_size
super(ContentTypeRestrictedFileField, self).__init__(**kwargs)
def clean(self, *args, **kwargs):
data = super(ContentTypeRestrictedFileField, self).clean(*args, **kwargs)
file = data.file
try:
content_type = file.content_type
if content_type in self.content_types:
if file._size > self.max_upload_size:
raise forms.ValidationError(_('Please keep filesize under %s. Current filesize %s') % (filesizeformat(self.max_upload_size), filesizeformat(file._size)))
else:
raise forms.ValidationError(_('Filetype not supported.'))
except AttributeError:
pass
return data
from south.modelsinspector import add_introspection_rules
add_introspection_rules([], ["^app\.extra\.ContentTypeRestrictedFileField"])
并添加此行 settings.py
FILE_UPLOAD_MAX_MEMORY_SIZE = 157286400 # 157286400 bytes = 150 MB
我被告知要使用this snippet,我找到this snippet
但是有一个我没看到的问题,djangosnippets用户说
If you're ok with letting people use up all your bandwidth for uploading 1GB
files to your servers just to delete them as soon as the upload finishes,
sure it's a great solution.
见this question。那个问题是关于asp.net,我使用django,那么如何在上传之前检测视频的文件大小,在django中
答案 0 :(得分:2)
您需要在点击Django之前切断HTTP上传,并且通常在您的前端Web服务器上执行此操作,该服务器可能是Apache,Nginx或其他任何内容,因此这个问题不是特定于Django的。
然而,最终的解决方案是使用HTML5 Javascript File API来读取客户端上的文件大小,并阻止用户在选择过大的文件时点击<form>
提交按钮:
https://developer.mozilla.org/en/DOM/File.size
由于较旧的浏览器不支持这两种方法,因此您仍需要回退Web服务器并假设未在每个浏览器上执行Javascript验证。
答案 1 :(得分:-1)
使用客户端编程, 之前检测视频的文件大小的 方式,你要么必须写Silverlight中的上传管理器o作为Java Applet(或在Flash中)或使用某些ActiveX o自定义浏览器特定的API