Environment Apache + mod_python
This method can be used if the file size is small.
Import OS
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> """
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
Failed t 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> "% Message
If the file size is large, multipart upload can be performed. Now it is an improved method.
Import OS
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> """
# Generator to buffer file chunks
Def fbuffer (F, chunk_size = 10000 ):
While true:
Chunk = f. Read (chunk_size)
If not Chunk: Break
Yield chunk
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
Failed t 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 ')
F = open (OS. Path. Join (dir_path, fname), 'wb', 10000)
# Read the file in chunks
For chunk in fbuffer (fileitem. File ):
F. Write (chunk)
F. Close ()
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> "% Message
From: http://long.objectis.net/wanglaoriji/yongpython-shixianshangzhuanwenjiangongneng