我有这段代码允许将文件上传到我网站上的特定目录,但是,我希望上传的每个文件(只会是 .txt 文件)重命名为“equations.txt”,然后下载到我的计算机,然后从服务器中删除。
例如,如果有人上传了一个名为“test.txt”的文件,我需要上传它,然后在我的服务器上将其重命名为“equations.txt”。
到目前为止,我已经上传了它,但是当我添加该行时:
os.renames('/home/xxxx/public_html/xxxx.com/test/uploads/' + fn, 'equations.txt')
它实际上完全删除了/uploads/
目录,而不是将目录中的文件重命名为“equations.txt”......这是代码:
#! /usr/bin/python
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('/home/xxxx/public_html/xxxx.com/test/uploads/' + fn, 'wb').write(fileitem.file.read())
message = "The file " + fn + " was uploaded successfully"
os.renames('/home/xxxx/public_html/xxxx.com/test/uploads/' + fn, 'equations.txt') ## Error line
else:
message = "No file was uploaded"
print ("""\
Content-type: text/html\n\n
<html>
<body>
<p>%s</p>
</body>
</html>
""") % (message)
如果没有在代码上方添加该行,则可以正常工作并将文件上传到/uploads/
目录。所以在我可以继续下一步之前,我需要重命名才能正常工作,谢谢。