【问题标题】:MultiValueDictKeyError for django image File uploaddjango图像文件上传的MultiValueDictKeyError
【发布时间】:2014-07-30 10:38:44
【问题描述】:

我花了很多时间试图解决这个问题——阅读 Django 文档,查阅表格,但没有得到任何令人满意的结果。所以请耐心等待我。 我正在尝试从我的 html 模板上传图像文件。 这是我的html表单

<form id="tryOnPageForm" method="POST" enctype="multipart/form-data" action="/dummy/{{frame.slug}}/">
{% csrf_token %}
  <input type="file" name="uploadFromPC" id="uploadFromPC" class="myButton" title="Upload From PC" value= "Upload from PC" onchange="uploadPC()" style="float:left;">
 <input type="submit" id="Submit" class="myButton" value= "Done" style="display:none"><br><br>

 </form>

文件上传正常,我可以在 HTML 中看到上传的图像文件。

在我的views.py

def upload_image(request, frameslug):

frame= v.objects.get(slug=frameslug)
if request.method == 'POST':
    form = ImageUploadForm(request.POST, request.FILES)
    print "FILES", request.FILES
    if form.is_multipart():
        save_file(request.FILES['image'])
        return HttpResponseRedirect('Successful')
    else:
        return HttpResponse('Invalid image')
else:
    form = ImageUploadForm()
return render_to_response('dummy.html', {'form': form})


def save_file(file, path=''):
    ''' Little helper to save a file
    '''
    filename = file._get_name()
    fd = open('%s/%s' % (MEDIA_ROOT, str(path) + str(filename)), 'wb')
    for chunk in file.chunks():
        fd.write(chunk)
    fd.close()

在我的forms.py

from django import forms
class ImageUploadForm(forms.Form):   
image = forms.ImageField(label='Select a file', help_text='max. 20 megabytes')

当我运行我的代码时,我得到了这个错误

MultiValueDictKeyError at /dummy/fr1234/

my from my view.py 中的 print 语句显示了这一点

FILES <MultiValueDict: {u'uploadFromPC': [<InMemoryUploadedFile: model4.jpg (image/jpeg)>]}>

这是回溯

Traceback:
File "C:\Python27\lib\site-packages\django\core\handlers\base.py" in get_response
  112.                     response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "D:\Work-Backup\LiClipse Workspace\vTryON_DJango_Integration\vTryON\views.py" in upload_image
  189.             save_file(request.FILES['image'])
File "C:\Python27\lib\site-packages\django\utils\datastructures.py" in __getitem__
  301.             raise MultiValueDictKeyError(repr(key))

Exception Type: MultiValueDictKeyError at /dummy/fr1234/
Exception Value: "'image'"

我知道 enctype 应该是 multipart/form-data,因为我已经在教程中阅读过它。另外,我没有使用 models.py 中的任何字段来存储上传的图像。相反,我想直接将其保存到 MEDIA_URL 位置。这可能是个问题吗? 请帮忙。这让我坚持了很长时间。提前致谢。

【问题讨论】:

    标签: python file-upload django-forms django-views


    【解决方案1】:

    我能够解决这个问题(花了很多时间并在朋友的帮助下...)

    我认为是错误

    Exception Type: MultiValueDictKeyError at /dummy/fr1234/ Exception Value: "'image'"

    来是因为request.FILES无法从用户输入中获取上传的图片,原因是我提供的用户输入文件名错误!!

    应该是 request.FILES['uploadFromPC'] 而不是 request.FILES['image'],因为这是我在 HTML 中保留的名称。

    <input type="file" name="uploadFromPC" id="uploadFromPC" class="myButton" title="Upload From PC" value= "Upload from PC" onchange="uploadPC()" style="float:left;">
    

    这是一个愚蠢的错误,浪费了很多时间来修复它.. :(

    .. 但是你,很好的学习。

    我希望这对尝试做类似事情的其他人有所帮助。虽然,如果有人可以在这里向我解释forms.py 的用法,我会很高兴。 是否可以在没有forms.py 的情况下进行用户上传?

    【讨论】:

      【解决方案2】:

      我发现当您提交表单而不选择文件时发生错误。如果未选择文件,则在您的情况下,input_name imageu''。这给出了错误,因为字典没有这样的键。
      我试图找到解决tryexcept错误的方法,但是python中没有这样的异常MultiValueDictKeyError

      【讨论】:

      • 我认为你应该尝试获取方法来获取数据并设置为默认值,例如 request.POST.get('name','default_value')
      【解决方案3】:
      request.FILES['file1']
      

      引发多值字典键错误,因此请检查您是否有如下 request.FILES 下的文件 -

      if request.method == "POST" and 'file1' in request.FILES and 'file2' in request.FILES:
      

      不要使用

      if request.method == "POST" and request.FILES['file1']:
      

      因为它也会引发错误

      【讨论】:

        猜你喜欢
        • 2014-05-14
        • 2018-04-01
        • 1970-01-01
        • 2014-06-14
        • 2011-03-21
        • 2010-10-02
        • 2013-05-13
        • 2019-09-01
        • 2017-03-31
        相关资源
        最近更新 更多