uploading multiple files with the same input name in django Sep
20
1
1

So sometimes I have an input field in a form that I want to upload files to but I want to upload multiple files at a time. I'll usually just use javascript to add and remove the field dynamically, and to keep things simple I'll keep the input name the same. I'll eventually end up with markup that looks similar to the following:

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

Django attaches the uploads in the FILE dictionary variable on the request object which you can access like so:

for uploaded_file in request.FILES['file']:
    # process the file

which could look something like:

# views.py
from django.http import HttpResponseRedirect

def upload_file(request):
    for uploaded_file in request.FILES.getlist('file'):
        handle_uploaded_file(uploaded_file)

    return HttpResponseRedirect(...)


def handle_uploaded_file(f):
    destination = open('/upload/path/%s' % f.name, 'wb+')

    for chunk in f.chunks():
destination.write(chunk) destination.close()
Bookmark and Share
blog comments powered by Disqus