开发者

Uploading multiple files in Django without using django.forms

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 t开发者_JAVA技巧here some trick to get to the other files? Am I stuck with a single file upload? Thanks!


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()
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜