使用Python使用cgi上传文件

时间:2016-10-27 08:55:23

标签: python file upload cgi

我尝试在此网站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,))

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

3 个答案:

答案 0 :(得分:0)

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

答案 1 :(得分:0)

此外,如果您要将图像上传到ec2 linux服务器,则要将文件上传到的文件夹必须具有权限 drwxrwxrwt

chmod 777 -R myfolder
chmod o+t -R myfolder

这对我有用

引自here

答案 2 :(得分:0)

也许问的人来晚了,但我遇到了类似的问题。以下是对我有用的内容。由于您的错误消息显示问题来自线路。 fileitem = form['filename'] 我们可以在浏览器中以 http://localhost:xxxx/file_upload.py 的形式运行文件。你会看到“浏览”按钮和“上传”按钮。除非您浏览并加载某个文件,否则不会填充“表单”对象。它还不会包含密钥“文件名”。我们得到了关键错误。所以我们需要把它放在一个 if 语句中。我还发现代码的 html 部分存在一些格式错误。我稍微编辑了下面粘贴的代码,在 Linux 上运行良好。

#!/usr/bin/python3
import cgi, sys, os
import cgitb; cgitb.enable()
form = cgi.FieldStorage()
print('Content-type: text/html')
sys.path.insert(0, os.getcwd())

message = None

# Test if the file is loaded for the upload
if 'filename' in form:
    fileitem = form['filename']
    fn = os.path.basename(fileitem.filename)
    open('/home/jk/' + fn, 'wb').write(fileitem.file.read())
    message = 'The file "' + fn + '" was uploaded successfully'
else:
    message = 'No file was uploaded'

replyhtml = """
<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" name=action/></p>
</form>
<p>%s</p>
</body>
</html>
"""
print(replyhtml % message)

我相信您的服务器在当前工作目录中运行。 .py 文件需要在 cgi-bin 文件夹中。一个简单的 http 服务器脚本:

import os
from http.server import HTTPServer, CGIHTTPRequestHandler

servaddr = ("localhost", 8888)
#http.server.SimpleHTTPRequestHandler(request, client_address, server)
server = HTTPServer(servaddr, CGIHTTPRequestHandler)
server.serve_forever()

参考文献:

  1. Python 编程,Mark Lutz,第 4 版,第 1 章
  2. https://www.youtube.com/watch?v=oQ9FwkhUN1s
  3. http://cgi.tutorial.codepoint.net/file-upload