Skip to main content
 首页 » 编程设计

python之使用 Python 和 cgi 上传文件

2025年04月02日8lidabo

我正在尝试在本网站中使用文件上传示例 https://www.tutorialspoint.com/python/python_cgi_programming.htm

我写了一个 .py 文件。当我运行这段代码时,出现以下错误;

Traceback (most recent call last): 
  File "C:/xampp/cgi-bin/file_upload.py", line 9, in <module> 
    fileitem = form['filename'] 
  File "C:\Python3\lib\cgi.py", line 604, in __getitem__ 
    raise KeyError(key) 
KeyError: 'filename' 

我的 .py 文件如下:

#!C:/Python3/python.exe 
 
import cgi, os 
import cgitb; cgitb.enable() 
 
form = cgi.FieldStorage() 
 
# Get filename here. 
fileitem = form['filename'] 
 
# Test if the file was uploaded 
if fileitem.filename: 
   # strip leading path from file name to avoid  
   # directory traversal attacks 
   fn = os.path.basename(fileitem.filename) 
   open('F:/gelen/' + fn, 'wb').write(fileitem.file.read()) 
 
   message = 'The file "' + fn + '" was uploaded successfully' 
 
else: 
   message = 'No file was uploaded' 
 
print ("""\ 
Content-Type: text/html\n 
<html> 
<body> 
    <form enctype="multipart/form-data"  
                     action="/cgi-bin/file_upload.py" method="post"> 
   <p>File: <input type="file" name="filename" /></p> 
   <p><input type="submit" value="Upload" /></p> 
   </form> 
   <p>%s</p> 
</body> 
</html> 
""" % (message,)) 

我如何解决这个问题以及为什么程序看不到我不理解的文件名

请您参考如下方法:

如果脚本运行的目录是/path/to/dir 那么/path/to/dir/files 目录必须存在。如果不这样做,它将失败。 并且要上传文件,HTML 表单必须将 enctype 属性设置为 multipart/form-data。