27
votes

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?

4
Same problem and solution for a single element with multiple: <input type="file" name="file" multiple />Mark

4 Answers

73
votes
for f in request.FILES.getlist('file'):
    # do something with the file f...

EDIT: I know this was an old answer, but I came across it just now and have edited the answer to actually be correct. It was previously suggesting that you could iterate directly over request.FILES['file']. To access all items in a MultiValueDict, you use .getlist('file'). Using just ['file'] will only return the last data value it finds for that key.

11
votes

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()
1
votes

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!

0
votes

This code is the example

    for f in request.FILES.getlist('myfile[]'):
        if request.method == 'POST' and f:
            myfile = f
            filesystem = FileSystemStorage()
            filename = filesystem.save(myfile.name, myfile)