1

我真的搜索了大约 50 个相关页面,但从未见过与我的问题类似的问题。当我按下提交按钮时,它调用脚本,但脚本返回一个空页面,我看到没有上传任何文件。我的代码中没有输入错误,我检查了几次,我真的需要为我的项目运行这段代码。可能是什么问题?我在ubuntu下运行apache,我的代码是:

html代码:

<html><body>
<form enctype="multipart/form-data" action="save_file.py" method="post">
<p>File: <input type="file" name="file"></p>
<p><input type="submit" value="Upload"></p>
</form>
</body></html>

蟒蛇代码:

#!/usr/bin/env python
import cgi, os
import cgitb; cgitb.enable()

try: #windows needs stdio set for binary mode
    import msvcrt
    msvcrt.setmode (0, os.O_BINARY)
    msvcrt.setmode (1, os.O_BINARY)
except ImportError:
    pass

form = cgi.FieldStorage()

#nested FieldStorage instance holds the file
fileitem = form['file']

#if file is uploaded
if fileitem.filename:
    #strip leading path from filename to avoid directory based attacks
    fn = os.path.basename(fileitem.filename)
    open('/files' + 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>
<p>%s</p>
</body></html>
""" % (message,)
4

1 回答 1

1

我刚刚测试了您的脚本,对路径进行了一些小的更正,使其在本地为我工作。正确设置路径并正确设置权限后,此代码可以正常工作。

以下是要确保的事项:

  1. 在您的 html 文件的表单属性中,确保您指向位于 cgi-bin: 中的 python 脚本action="/cgi-bin/save_file.py"。对我来说,我的 Web 服务器的根目录有一个 cgi-bin,我将 python 脚本放在那里。如果您从 Web 服务器上的标准文档位置运行脚本,它将不起作用

  2. 确保您的 save_file.py 具有可执行权限:chmod 755 save_file.py

  3. 在您的 save_file.py 中,确保您正在构建一个有效路径来打开文件进行保存。我将我的绝对设置为仅用于测试目的,但是是这样的:open(os.path.join('/path/to/upload/files', fn)

正确设置这些点,您应该没有任何问题。

于 2012-06-03T18:02:04.377 回答