django study notes multiple file uploads

 

Accustomed to the flask and then django still not used to good trouble Profiles Intuit more

 

But still to learn

Only a file before a long pass, this time to try multiple files

 

NA django of forms to create a form 
to be used directly in html

 <form Action = " / " Method = " POST " the enctype = " multipart / form-Data " > 
    { % csrf_token% }
    
     <INPUT type = " File " name = " IMG " Multiple = " " > 
    <= the INPUT of the type " the Submit " value = " upload pictures " > 
</ form>
The biggest change is in the position to add a file 

Multiple = ""      This represents a long pass multiple files, if you do not add this file is a long pass

 <the INPUT of the type = " File " name = " img " Multiple = "" >

 

View function settings

DEF index (Request): 

    IF request.method == ' the POST ' :
         # plurality of file objects need to get an object recycling getlist   
        Files = request.FILES.getlist ( ' IMG ' )    
         for F in Files:
             Print (F) printouts the name of the file object
     return the render (Request, ' base.html ' )

But this is not enough, do not file filter

def index(request):
allow = ['jpg','gif','png']
if request.method == 'POST':
files = request.FILES.getlist('img')
for f in files:      # 限制文件格式
if f.name.split('.')[-1] not in allow:
continue
else:      # 限制文件大小
if f.size > MAX_UPLOAD_SIZE:
continue
path_img = open(os.path.join(MEDIA_ROOT,f.name),'wb+')
for chunk in f.chunks():
path_img.write(chunk)
path_img.close()
return render(request, 'base.html')
MAX_UPLOAD_SIZE provided in the settings file
MAX_UPLOAD_SIZE = 5242880/10 # 5242880 file size is 5m, you can set up their own if there is a demand, I am here to experiment / 10 
ALLOW_IMG_UP = [ ' JPG ' , ' GIF ' , ' PNG ' ]

 

 

However, because the form is not the forms, it is not an error message flashed directly in html, if you can please use the form forms of

https://www.cnblogs.com/mosson/p/11059149.html

 

Guess you like

Origin www.cnblogs.com/zengxm/p/11294438.html