2016-08-09 40 views
0

Ich erstelle eine Methode, die eine Datei hochlädt, aber ich möchte die Dateigröße überprüfen, da ich nur 5 MB als maximale Grenze zulassen möchte.So überprüfen Sie die Dateigröße in django

ich so etwas wie diese

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

Zusammen mit Ihrem Django prüft, empfehle ich auch einige Server-Ebene Konfigurationen Hinzufügen von Datei-Upload-Größe zu begrenzen (z seting 'client_max_body_size' in nginx). –

Antwort

3

Verwenden ._size Dateiattribut

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

._size in Bytes dargestellt wird. 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

Vielen Dank, aber ich habe diese Fehlermeldung unorderable Typen: int()> str() –

+0

@JamesReid Ich habe behoben, meine schlechte, müssen Sie 5242880 als Int nicht String '5242880' – levi

+0

Vielen Dank. Das ist wirklich eine große Hilfe ... @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 

Kredite machen will geht an django snippet

+1

seien Sie vorsichtig, 'MAX_UPLOAD_SIZE' ist ein String und' ._size' gibt einen int zurück. – levi

+0

Vielen Dank für das, @levi. Ich habe gerade MAX_UPLOAD_SIZE zu einem int geändert. – user4426017