Reputation: 123
I have this code which allows uploading of files to a specific directory on my website, however, I want every file that is uploaded (which will only be a .txt file) to be renamed to "equations.txt" and then downloaded to my computer and then deleted from the server.
I need for example if someone uploads a file called "test.txt", it should upload it and then rename it to "equations.txt" on my server.
So far right now I got it to upload, but when I add the line:
os.renames('/home/xxxx/public_html/xxxx.com/test/uploads/' + fn, 'equations.txt')
It actually deletes the /uploads/
directory entirely instead of renaming the file in the directory to "equations.txt"...Here is the code:
#! /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)
Without the line added above the code works fine and uploads files to the /uploads/
directory. So before I can move on to the next steps I need the renaming to work properly, thanks.
Upvotes: 1
Views: 1466
Reputation: 18128
Have you tried os.rename
instead of os.renames
?
Also, try an absolute path for the dest. So, this:
dest_dir = '/home/xxxx/public_html/xxxx.com/test/uploads/'
os.rename(dest_dir + fn, dest_dir + 'equations.txt')
instead of this:
os.renames('/home/xxxx/public_html/xxxx.com/test/uploads/' + fn, 'equations.txt')
Upvotes: 1