PDA

View Full Version : Python - file uploading..


Benny
04-23-2002, 11:25 AM
Hey all,

Was wondering how I can get cgi file uploading working using python (for uploading images to a webserver)...I thought I could do something like this:


photodir = "\images\photo"

def fileUpload():
form = cgi.FieldStorage()

if not form.has_key("file"):

print "content-type: text/html\n"
print """
<head>
<title>File Upload</title>
<body>



Upload your image</p>
<form action="stamps.py" method="POST" enctype="multipart/form-data">
<input type="hidden" name="sessionvalue" value="3">
Name of File: <input name="file" type="file" size="35">

<input name="submit" type="submit" value="Upload Image">
</form>
</body>
</html>
"""
else:
print "content-type: text/html\n"
if not os.path.exists(photodir):
os.mkdir(photodir,0777)

fn = form["file"].filename
if string.rfind(form["file"].filename,"\\") >= 0:
fn = fn[string.rfind(form["file"].filename,"\\"):]
if string.rfind(form["file"].filename,"/") >= 0:
fn = fn[string.rfind(form["file"].filename,"/"):]
if string.rfind(form["file"].filename,":") >= 0:
fn = fn[string.rfind(form["file"].filename,":"):]

o = open(photodir+os.sep+fn, "w")
o.write(form["file"].value)
o.close()
print "File uploaded"


But this method only seems to work for small text files, anything else and the file doesn't upload correctly (I want to use it for images only, so it's no good to me)....I saw the "cgiupload.py" module on the Python site, but I am unsure as to it's operation....?

Some feedback/advice would be much apprieciated.

Cheers.

kmj
04-23-2002, 04:26 PM
When you open your image files, are you opening them in binary mode? If I'm not mistaken, you have to specify binary mode, as text mode is used by default. I.e., your string should read "wb" if you want to write an image file, not just "w".

Benny
04-24-2002, 01:48 AM
oops yeh, initially I had "wb" and it wasn't working, then I tried removing the b and it still wasn't working.....must have forgotten to put it back.

But yeh, even with the "b" it still didn't work.....

Thanks though.

Benny
04-25-2002, 01:59 AM
Okay interesting situation.....

Initially I was trying the upload stuff with python 2.2.1 and Apache 2.0.35, both running on Windows XP (I just access the site locally (127.0.0.1)).......thats where it worked for only text stuff but nothing binary such as an image, zip file etc etc.

I just tested it on my Linux server (running python 1.5 and apache 1.3) and it worked, the image uploaded perfectly.....

So why is it that it wont work with my initial set-up (the set-up I need it to work for), would it be something to do with my apache settings or just the fact that it is a windows platform??

Any ideas?

Cheers

Benny
04-25-2002, 02:36 AM
Whooooooooo fixed it.

If using python for cgi on a windows platform the script must be executed using:

python.exe -u

That fixed my problem....8)

kmj
04-25-2002, 09:21 AM
qool (c: