I did this recently using the CGI module in Python.
My POST method and file copy process are below.
It uses a form, where sfname is the full path of where the file had to saved and file is the file itself. This is slightly more complex than what you need, but it should get you going.
def do_POST(self):
f = StringIO()
fm = cgi.FieldStorage(fp=self.rfile, headers=self.headers, environ={'REQUEST_METHOD':'POST'})
if "file" in fm:
r, resp, info = self.get_file_data(fm)
print r, info, "by: ", self.client_address
if r:
f.write("File upload successful: %s" % info)
f.seek(0)
if resp == 200:
# Do stuff here
else:
# Error handle here
else:
f.write("File upload failed: %s" % info)
f.seek(0)
if resp == 200:
# Do stuff here
else:
# Error handle here
if f:
copyfileobj(f, self.wfile)
f.close()
else:
# Error handle here
def get_file_data(self, form):
fn = form.getvalue('sfname')
fpath, fname = ospath.split(fn)
if not ospath.isabs(fpath):
return (False, 400, "Path of filename on server is not absolute")
if not ospath.isdir(fpath):
return (False, 400, "Cannot find directory on server to place file")
try:
out = open(fn, 'wb')
except IOError:
return (False, 400, "Can't write file at destination. Please check permissions.")
out.write(form['file'].file.read())
return (True, 200, "%s ownership changed to user %s" % (fn, u))
Also, this were the packages I imported. You might not need all of them.
from shutil import copyfileobj
from os import path as ospath
import cgi,
import cgitb; cgitb.enable(format="text")
try:
from cStringIO import StringIO
except ImportError:
from StringIO import StringIO
I tested it with curl -F "file=@./myfile.txt" -F "sfname=/home/user/myfile.txt" http://myserver and it worked fine. Can't guarantee the other methods. Hope this helps.