File: file_upload.py

package info (click to toggle)
pythoncard 0.8.1-8.1
  • links: PTS
  • area: main
  • in suites: etch, etch-m68k, lenny
  • size: 5,352 kB
  • ctags: 4,594
  • sloc: python: 42,401; makefile: 55; sh: 22
file content (44 lines) | stat: -rw-r--r-- 1,266 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
#!/usr/bin/python

import cgi, sys, os

UPLOADSSDIR = '..' + os.sep + 'uploads'

form = cgi.FieldStorage()
fileitem = form["input_file"]

print "Content-type: text/html\r\n\r\n",

print "<HTML><HEAD><TITLE>File Upload Result</TITLE></HEAD><BODY>"

if fileitem.filename and fileitem.file:
    # it is important to restrict uploads to a particular
    # user-specified directory rather than using
    # the path of the uploaded file
    # the extension could still be bogus or the contents
    # could contain a virus, trojan, etc., but that
    # is something the user has to watch out for
    
    dir = UPLOADSSDIR
    
    target = fileitem.filename
    target = target.replace(':', '/')
    target = target.replace('\\', '/')
    filename = target.split('/')[-1]

    try:
        path = os.path.join(dir, filename)
        # we could check for file existance and not write the file
        # if it already exists
        fp = open(path, 'wb')
        fp.write(fileitem.file.read())
        fp.close()

        print "Upload of file %s was successful." % filename
    except:
        print "Upload of file %s failed." % filename
        
else:
    print "Please provide a file to upload. Hit the Back button in your browser to try again."

print "</BODY></HTML>"