代码之家  ›  专栏  ›  技术社区  ›  Abu Aqil

在Django中使用相同输入名上载多个文件

  •  17
  • Abu Aqil  · 技术社区  · 15 年前

    我在上载多个输入名相同的文件时遇到问题:

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

    在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)>
    ]}>
    

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

    3 回复  |  直到 15 年前
        1
  •  55
  •   SmileyChris    13 年前
    for f in request.FILES.getlist('file'):
        # do something with the file f...
    

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

        2
  •  9
  •   user191104    15 年前

    如果你的网址指向 恩维亚 您可以这样管理多个文件:

    #!/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()
    
        3
  •  1
  •   Community CDub    7 年前

    我不认为这三份文件都在这张单子下面 request.FILES['file'] 对象。 请求.files['file'] 可能有该列表中的第一个文件或最后一个文件。

    您需要唯一地命名输入元素,如:

    <input type=file name="file1">
    <input type=file name="file2">
    <input type=file name="file3">
    

    例如…

    编辑: Justin's answer 更好!