我真的搜索了大约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>
python代码:
#!/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,)
答案 0 :(得分:1)
我刚测试了你的脚本,对路径进行了一些小的修改,使它在本地工作。正确设置路径并正确设置权限后,此代码可以正常工作。
以下是要确保的事项:
在html文件的表单属性中,确保指向位于cgi-bin中的python脚本:action="/cgi-bin/save_file.py"
。对我来说,我的Web服务器的根目录下有一个cgi-bin,我把python脚本放在那里。如果从Web服务器上的标准文档位置运行脚本,它将无法工作
确保save_file.py具有可执行权限:chmod 755 save_file.py
在save_file.py中,确保构建有效路径以打开要保存的文件。我只是出于测试目的而做了我的绝对,但是这样的事情:open(os.path.join('/path/to/upload/files', fn)
正确设置这些点后,你不应该有任何问题。