views:

1809

answers:

4

hello there,

i m having trouble in uploading multiple files with same input name:

<input type=file name="file">
<input type=file name="file">
<input type=file name="file">

at django side

print request.FILES :

<MultiValueDict: {u'file': [
<TemporaryUploadedFile: captcha_bg.jpg (image/jpeg)>,
<TemporaryUploadedFile: 001_using_git_with_django.mov (video/quicktime)>,
<TemporaryUploadedFile: ejabberd-ust.odt (application/vnd.oasis.opendocument.text)>
]}>

so all three files are under single request.FILES['file'] object . how do i handle for each files uploaded from here?

+1  A: 

I dont think all three files will be under the single request.FILES['file'] object. request.FILES['file'] is likely to have either the 1st file or the last file from that list.

You need to uniquely name the input elements like so:

<input type=file name="file1">
<input type=file name="file2">
<input type=file name="file3">

..for example.

EDIT: Justin's answer is better!

cottsak
Django automatically handles the case where multiple inputs have the same name: it hands your code a list of values instead of a single value. You can see the list in the code that was posted.
Justin Voss
So this 'MultiValueDict' is the result of maybe a wrapper to the request.FILES['file'] object then?
cottsak
Yes, request.FILES is a MultiValueDict object, while request.GET and request.POST are QueryDict objects, which are similar.
Justin Voss
Kool. Didn't know that. I'll update my answer.
cottsak
+6  A: 

The output you posted shows that request.FILES['file'] is a list, so iterate over it:

for f in request.FILES['file']:
    # do something with the file f...
Justin Voss
+2  A: 

Given your url points to envia you could manage multiple files like this:

#!/usr/bin/env python
# -*- coding: UTF-8 -*-
from django.http import HttpResponseRedirect

def envia(request):
    for f in request.FILES.getlist('file'):
        handle_uploaded_file(f)
    return HttpResponseRedirect('/bulk/')

def handle_uploaded_file(f):
    destination = open('/tmp/upload/%s'%f.name, 'wb+')
    for chunk in f.chunks():
        destination.write(chunk)
    destination.close()
aaloy