django图像的MultiValueDictKeyError文件上传

[英]MultiValueDictKeyError for django image File upload


I have spent a LOT of time trying to resolve this- Read Django docs, consulted forms but not got anything satisfactory. So please be patient here with me. I am trying to do an upload of an Image file here from my html template. This is my html form

我花了很多时间试图解决这个问题 - 阅读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>

The file upload happens properly an d I am able to see the uploaded image file in the HTML.

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

In my views.py,

在我的views.py中,

def upload_image(request, frameslug):

frame= VTryON.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()

and in my forms.py,

在我的forms.py中,

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

When I run my code I get this error

当我运行我的代码时,我收到此错误

MultiValueDictKeyError at /dummy/fr1234/

The print statement in my from my view.py shows this

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

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

and this is the traceback

这是追溯

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'"

I am aware that the enctype should be multipart/form-data since I have read it in tutorials. ALso, i have not used any field in my models.py to store the uploaded image.Instead I want to directly save it to thr MEDIA_URL location.Might that be an issue? Please help. This has held me up for a long time. Thanks in advance.

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

2 个解决方案

#1


6  

I was able to solve this(after spending a lot of time and with some help from my friends...)

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

I think the error

我认为错误

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

异常类型:/ dummy / fr1234处的MultiValueDictKeyError /异常值:“'image'”

was coming because request.FILES was unable to get the uploaded image from the user input, the reason being that the name of the user input file that I provided was wrong!!

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

It should have been request.FILES['uploadFromPC'] instead of request.FILES['image'] because that is the name that I had kept in my HTML.

应该是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;">

That was a stupid error and a lot of time wasted to fix it.. :(

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

.. but ya, good learning.

..但是,好的学习。

I hope this helps somebody else who is trying to do something similar. Although, I would like it if somebody can explain to me the use of forms.py here. Is it possible to do an user upload without forms.py?

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

#2


1  

I found that the error occurs when you submit the form without selecting the file. when a file is not selected then the input_name in your case image is u''. this gives the error as the dictionary has no such key.
i tried to find a way to try and except error but there is no such exception in python MultiValueDictKeyError

我发现在没有选择文件的情况下提交表单时会发生错误。如果未选择文件,则案例图像中的input_name为u''。这给出了错误,因为字典没有这样的键。我试图找到一种方法来尝试除了错误,但在python MultiValueDictKeyError中没有这样的异常


注意!

本站翻译的文章,版权归属于本站,未经许可禁止转摘,转摘请注明本文地址:https://www.itdaan.com/blog/2014/07/30/720bbfb2658683de150f7ec5543c8b66.html



 
粤ICP备14056181号  © 2014-2021 ITdaan.com