[python] upload binary files-Win32/Abyss+ActivePython how-to

 
Post new topic   Reply to topic    Aprelium Forum Index -> Tutorials
View previous topic :: View next topic  
Author Message
nicolas
-


Joined: 12 Aug 2008
Posts: 2

PostPosted: Tue Aug 12, 2008 10:23 am    Post subject: [python] upload binary files-Win32/Abyss+ActivePython how-to Reply with quote

HTML upload script (example) - don't forget the multipart/form-data encoding type and the max value file size - :

<!DOCTYPE html>
<html lang="en">
<head>
<meta content="text/html; charset=utf-8" http-equiv="content-type" />
<title>Upload Form Page</title>
</head>
<body>
<H2>Upload File</H2><P>
<FORM ENCTYPE="multipart/form-data" METHOD="POST" ACTION="upload.py">
<INPUT TYPE="hidden" NAME="MAX_FILE_SIZE" VALUE="2048">
<INPUT TYPE="file" SIZE="70" NAME="uFile">
<P><INPUT TYPE="SUBMIT" VALUE="upload">
</FORM>
</body>
</html>

Python upload script (example derived from ISBN-13: 978-2744021497 book) :

#!/usr/bin/python
import cgi, os, sys, string
import posixpath, macpath # modify here to fit you os.

## here is the tip for Win32 bin uploads ##
import cgitb; cgitb.enable()
import msvcrt, os
msvcrt.setmode (0, os.O_BINARY)
msvcrt.setmode (1, os.O_BINARY)
############################

saveDir = "../your_directory" # modify your target directory

#Send errors to browser
sys.stderr = sys.stdout

#Parse data from form
data = cgi.FieldStorage()

#Save the file to server directory
def saveFile(uFile):
fPath = "%s/%s" % (saveDir, uFile.filename)
buf = uFile.file.read()
sFile = open(fPath, 'wb')
sFile.write(buf)
sFile.close()


#Send response to brower
webText = """Content-type: text/html\n"
<TITLE>CGI Upload Form</TITLE>\n
<H2>Upload File</H2><P>"""
print webText

if data.has_key('uFile'):
saveFile(data['uFile'])
print "<B>%s</B> uploaded." % (data['uFile'].filename)
Back to top View user's profile Send private message
Display posts from previous:   
Post new topic   Reply to topic    Aprelium Forum Index -> Tutorials All times are GMT + 1 Hour
Page 1 of 1

 
Jump to:  
You cannot post new topics in this forum
You cannot reply to topics in this forum
You cannot edit your posts in this forum
You cannot delete your posts in this forum
You cannot vote in polls in this forum


Powered by phpBB phpBB Group