3

So I've created a form that includes the following item

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

This tells the browser to allow the user to select multiple files while browsing. The problem I am having is is that when reading / writing the files that are being uploaded, I can only see the last of the files, not all of them. I was pretty sure I've seen this done before, but had no luck searching. Here's generally what my read looks like

if request.FILES:
    filename = parent_id + str(random.randrange(0,100))
    output_file = open(settings.PROJECT_PATH + "static/img/inventory/" + filename + ".jpg", "w")
    output_file.write(request.FILES["form_file"].read())
    output_file.close()

Now, as you can see I'm not looping through each file, because I've tried a few different ways and can't seem to find the other files (in objects and such)

I added in this print(request.FILES["form_file"]) and was only getting the last filename, as expected. Is there some trick to get to the other files? Am I stuck with a single file upload? Thanks!

1 Answer 1

6

Based on your file element form_file, the value in request.FILES['form_file'] should be a list of files. So you can do something like:

for upfile in request.FILES.getlist('form_file'):
    filename = upfile.name
    # instead of "filename" specify the full path and filename of your choice here
    fd = open(filename, 'w')
    fd.write(upfile['content'])
    fd.close()

Using chunks:

for upfile in request.FILES.getlist('form_file'):
    filename = upfile.name
    fd = open(filename, 'w+')  # or 'wb+' for binary file
    for chunk in upfile.chunks():
        fd.write(chunk)
    fd.close()
Sign up to request clarification or add additional context in comments.

14 Comments

I tried that, but only got bits of the file, or "chunks" I think they call them in django. It was pretty weird, I had to switch to this method to actually get the entire file. The chunks were 4kb.
Maybe you can try the recipe for handling chunks mentioned in the docs : docs.djangoproject.com/en/dev/topics/http/file-uploads/…
When dealing with chunks, how do I know when I'm finished my first file, and starting my second?
I've tried that, but upfile is a string no matter what (when I upload a single file, or multiple files) which is why I can't do chunks() on it.
When I print request.FILES when uploading 1 file: <MultiValueDict: {u'form_file': [<InMemoryUploadedFile: n556057924_592062_5411.jpg (image/jpeg)>]}> and when uploading 2 files <MultiValueDict: {u'form_file': [<InMemoryUploadedFile: n556057924_839946_4670.jpg (image/jpeg)>, <InMemoryUploadedFile: n556057924_839947_4940.jpg (image/jpeg)>]}>
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.