服务器怎么接受file文件,仅在服务器端的FileField中接受某种文件类型

小智..

7

第一.在应用程序内创建一个名为formatChecker.py的文件,其中包含具有要接受某种文件类型的FileField的模型.

这是你的formatChecker.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, *args, **kwargs):

self.content_types = kwargs.pop("content_types")

self.max_upload_size = kwargs.pop("max_upload_size")

super(ContentTypeRestrictedFileField, self).__init__(*args, **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

第二.在models.py中,添加以下内容:

from formatChecker import ContentTypeRestrictedFileField

然后使用'ContentTypeRestrictedFileField'代替使用'FileField'.

例:

class Stuff(models.Model):

title = models.CharField(max_length=245)

handout = ContentTypeRestrictedFileField(upload_to='uploads/', content_types=['video/x-msvideo', 'application/pdf', 'video/mp4', 'audio/mpeg', ],max_upload_size=5242880,blank=True, null=True)

当您只想接受FileField中的某种文件类型时,这些是您必须要做的事情.

在超级调用之前添加此行:self.widget = ClearableFileInput(attrs = {'accept':','.join(self.content_types)})将仅在模式窗口中选择可接受的内容类型. (3认同)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值