Skip to main content
 首页 » 编程设计

Python文件上传 "KeyError"

2025年05月04日9Leo_wl

这段代码有什么问题?

这是我的 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" value="Upload" name="submit"></p> 
</form> 
</body></html> 

这是我的 Python 脚本:

#! /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"] 
..... 

这是我得到 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' 

请您参考如下方法:

编辑:完全错过了您正在执行 keep_blank_values = 1 的部分;抱歉,不知道出了什么问题。

来自 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.

因此,发生这种情况是因为此字段留空。