lost and found ( for me ? )

apache mod_python : upload files over post method

many thanks!

root@ubuntu-vm2:~# tail -1 /etc/lsb-release ;uname -ri
DISTRIB_DESCRIPTION="Ubuntu 12.04.2 LTS"
3.2.0-49-virtual x86_64
root@ubuntu-vm2:~# apache2ctl -v
Server version: Apache/2.2.22 (Ubuntu)
Server built:   Jul 12 2013 13:37:10

on the apache server, place the following python script under /var/www/python_works directory.
root@ubuntu-vm2:~# cat /var/www/python_works/index.py
import os

s = """\
<html><body>
<h2>Hello %s!</h2>
</body></html>
"""

def index():
  return s % 'World'
  
def everybody():
  return s % 'everybody'

def form():
  return """\
<html><body>
<form enctype="multipart/form-data" action="./upload" method="post">
<p>File: <input type="file" name="file"></p>
<p><input type="submit" value="Upload"></p>
</form>
</body></html>
"""

def upload(req):
  
  try: # Windows needs stdio set for binary mode.
     import msvcrt
     msvcrt.setmode (0, os.O_BINARY) # stdin  = 0
     msvcrt.setmode (1, os.O_BINARY) # stdout = 1
  except ImportError:
     pass

  # A nested FieldStorage instance holds the file
  fileitem = req.form['file']

  # Test if the file was uploaded
  if fileitem.filename:

     # strip leading path from file name to avoid directory traversal attacks
     fname = os.path.basename(fileitem.filename)
     # build absolute path to files directory
     dir_path = os.path.join(os.path.dirname(req.filename), 'files')
     open(os.path.join(dir_path, fname), 'wb').write(fileitem.file.read())
     message = 'The file "%s" was uploaded successfully' % fname

  else:
     message = 'No file was uploaded'
  
  return """\
<html><body>
<p>%s</p>
<p><a href="./form">Upload another file</a></p>
</body></html>
""" % message
root@ubuntu-vm2:~#



make directory under /var/www/python_works.
uploaded files are copied to /var/www/python_works/files directory.
root@ubuntu-vm2:/var/www/python_works# pwd
/var/www/python_works
root@ubuntu-vm2:/var/www/python_works# mkdir files

root@ubuntu-vm2:/var/www/python_works# chmod 777 files/

access to http://apache IP/python_works/index.py/form


select a file you would like to upload to the apache server and then click “Upload”



15M.png was copied to /var/www/python_works/files directory.

root@ubuntu-vm2:~# ls /var/www/python_works/files/
15M.png


No comments:

Post a Comment

Note: Only a member of this blog may post a comment.