【问题标题】:File upload using Python with cgi使用 Python 和 cgi 上传文件
【发布时间】:2017-03-09 21:09:30
【问题描述】:

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

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

【问题讨论】:

    标签: python file upload cgi


    【解决方案1】:

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

    【讨论】:

      【解决方案2】:

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

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

      这对我有用

      转自here

      【讨论】:

        【解决方案3】:

        也许问的人已经晚了,但我遇到了类似的问题。以下是对我有用的。正如您的错误消息显示的那样,问题来自线路。 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

        【讨论】:

          猜你喜欢
          • 2015-02-15
          • 1970-01-01
          • 2011-06-20
          • 2013-12-24
          • 1970-01-01
          • 1970-01-01
          • 2014-07-06
          • 2012-09-07
          • 2012-10-27
          相关资源
          最近更新 更多