我有这个代码,允许将文件上传到我网站上的特定目录,但是,我希望将上传的每个文件(只有.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/
目录。因此,在我继续执行下一步之前,我需要重命名才能正常工作,谢谢。
答案 0 :(得分:1)
您是否尝试过os.rename
而不是os.renames
?
另外,尝试dest的绝对路径。所以,这个:
dest_dir = '/home/xxxx/public_html/xxxx.com/test/uploads/'
os.rename(dest_dir + fn, dest_dir + 'equations.txt')
而不是:
os.renames('/home/xxxx/public_html/xxxx.com/test/uploads/' + fn, 'equations.txt')