Python file upload "KeyError"
Whats wrong in this code?
Here is my HTML:
<html><body>
<form action="iindex.py" method="POST" enctype="multipart/form-data">
<p>File: <input type="file" name="ssfilename"></p>
<p><input type="submit" v开发者_StackOverflow中文版alue="Upload" name="submit"></p>
</form>
</body></html>
This is my Python script:
#! /usr/bin/env python
import os, sys;
from mod_python import apache
import cgi
import cgitb; cgitb.enable()
form = cgi.FieldStorage(keep_blank_values=1)
fileitem = form["ssfilename"]
.....
This is the line where I get KeyError.
File "/Applications/MAMP/python/framework/Python.framework/Versions/2.6/lib/python2.6/cgi.py", line 541, in __getitem__
raise KeyError, key
KeyError: 'ssfilename'
Edit: Totally missed the part where you are doing keep_blank_values = 1
; sorry, no idea what is wrong.
From http://docs.python.org/library/cgi.html:
Form fields containing empty strings are ignored and do not appear in the dictionary; to keep such values, provide a true value for the optional keep_blank_values keyword parameter when creating the FieldStorage instance.
Therefore, this is happening because this field was left blank.
I had the exact same problem, make sure you have the "enctype" set to "multipart/form-data" and use a default value in your field. So your form should look like this:
<form enctype="multipart/form-data" id="addFile" action="AddFile.py">
<input type="file" name="file" id="file" value=""/><br/>
<input type="submit" name="submit" value="Add File"/><br/>
</form>
I was also using a JQuery handler for my Form and was trying to serialize it and then posting it to my python handler, I bypassed that and it was going all fine, so you should try that also.
Check if you have no GET parameters in your form action URL.
If you need to pass on any data put it as form elements inside the form to be POSTed along with your upload file.
Then you find all your POSTed vars in cgi.FieldStorage
.
精彩评论