在django中使用相同的输入名称上载多个文件

Abu*_*qil 20 django upload file-upload file

我在上传具有相同输入名称的多个文件时遇到问题:

<input type=file name="file">
<input type=file name="file">
<input type=file name="file">
Run Code Online (Sandbox Code Playgroud)

在django一边

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)>
]}>
Run Code Online (Sandbox Code Playgroud)

所以这三个文件都在单个request.FILES ['file']对象下.我如何处理从这里上传的每个文件?

Jus*_*oss 62

for f in request.FILES.getlist('file'):
    # do something with the file f...
Run Code Online (Sandbox Code Playgroud)

编辑:我知道这是一个古老的答案,但我刚才遇到它,并编辑了答案,实际上是正确的.以前建议您可以直接迭代request.FILES['file'].要访问MultiValueDict中的所有项目,请使用.getlist('file').使用just ['file']只会返回它为该键找到的最后一个数据值.


小智 10

鉴于您的网址指向envia,您可以管理多个文件,如下所示:

#!/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()
Run Code Online (Sandbox Code Playgroud)

  • 您不应该使用用户提供的文件名在磁盘上写入,它可能会被操纵以在任何地方写入。使用随机文件名并将原始文件名存储在数据库中仅用于演示目的 (2认同)