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
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 = """\
<h2>Hello %s!</h2>

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

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

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:

  # 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

     message = 'No file was uploaded'
  return """\
<p><a href="./form">Upload another file</a></p>
""" % message

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
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/

No comments:

Post a Comment

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