2016-08-09 33 views
0

我正在創建一個上傳文件的方法,但是我想檢查文件大小,因爲我只是想允許5mb作爲最大限制。如何檢查django中的文件大小限制

我想讓這樣的事情

def handle_uploaded_file(thisFile): 
    if thisFile > 5mb: 
     return "This file is more than 5mb" 
    else: 
     with open('some/file/' + str(thisFile), 'wb+') as destination: 
      for chunk in thisFile.chunks(): 
       destination.write(chunk) 
     return "File has successfully been uploaded" 
+0

隨着你的Django的檢查,我還建議加入一些服務器級別配置,以限制上傳文件大小(例如塞汀'client_max_body_size'在nginx的)。 –

回答

3

使用._size文件屬性

if thisFile._size > 5242880: 
    return "This file is more than 5mb" 

._size以字節爲單位表示。 5242880 - 5MB

def handle_uploaded_file(thisFile): 
    if thisFile._size > 5242880: 
     return "This file is more than 5mb" 
    else: 
     with open('some/file/' + str(thisFile), 'wb+') as destination: 
      for chunk in thisFile.chunks(): 
       destination.write(chunk) 
     return "File has successfully been uploaded" 
+0

非常感謝你,但是我得到了這個錯誤消息無法訂購的類型:int()> str() –

+0

@JamesReid我修正了,我的不好,你需要使用5242880作爲int而不是字符串'5242880' – levi

+0

非常感謝。這真的是一個很大的幫助...... @levi –

4
# Add to your settings file 
CONTENT_TYPES = ['image', 'video'] 
# 2.5MB - 2621440 
# 5MB - 5242880 
# 10MB - 10485760 
# 20MB - 20971520 
# 50MB - 5242880 
# 100MB 104857600 
# 250MB - 214958080 
# 500MB - 429916160 
MAX_UPLOAD_SIZE = 5242880 

#Add to a form containing a FileField and change the field names accordingly. 
from django.template.defaultfilters import filesizeformat 
from django.utils.translation import ugettext_lazy as _ 
from django.conf import settings 
def clean_content(self): 
    content = self.cleaned_data['content'] 
    content_type = content.content_type.split('/')[0] 
    if content_type in settings.CONTENT_TYPES: 
     if content._size > settings.MAX_UPLOAD_SIZE: 
      raise forms.ValidationError(_('Please keep filesize under %s. Current filesize %s') % (filesizeformat(settings.MAX_UPLOAD_SIZE), filesizeformat(content._size))) 
    else: 
     raise forms.ValidationError(_('File type is not supported')) 
    return content 

幸得django snippet

+1

要小心,'MAX_UPLOAD_SIZE'是字符串,'._size'返回一個int。 – levi

+0

感謝您指出這一點,@levi。我只是將MAX_UPLOAD_SIZE更改爲int。 – user4426017

相關問題