views:

33

answers:

3

Hi, I have created a test form which will ask users to enter a name and upload the image file:

<html lang="en">
<head>
    <title>Testing image upload</title>
</head>
<body>
    <form action="/services/upload" method="POST" enctype="multipart/form-data">
    File Description: <input name='fdesc' type='text'><br>
    File name: <input type="file" name="fname"><br>
    <div><input type="submit"></div>
    </form>
</body>
</html>

i need to get the file uploaded by the user and store it on my local PC. can this be done in python ? please let me know.

+1  A: 

mod_python includes the FieldStorage class which allows you access to uploaded form data. In order to use it, you'd put something like the following in your Python script:

req.form = FieldStorage(req)
description = req.form['fdesc']

Since fdesc is a text input, description will be a string (more precisely, a StringField, which you can treat as a string).

file_field = req.form['fname']

Since fname is a file input, file_field will not be a string (or StringField), but rather a Field object which allows you access to the file data. The attribute file_field.file is a file-like object which you can use to read the file's contents, for example like so:

for line in file_field.file:
    # process the line

You could use this to copy the file's data somewhere of your choosing, for example.

file_field.filename is the name of the file as provided by the client. Other useful attributes are listed in the documentation I linked to.

David Zaslavsky
David, I am not able to get it working, i think i am doing it wrong way, can you give me some example.
Suhail
I did. There are a few lines of example code in my answer and there are more complete examples at the links I gave you. If you've gone through those and haven't been able to figure out why your code isn't working, post a new question (since "why doesn't this work" is a separate question from "how do I do it"), and make sure to include your code and the details of your error message.
David Zaslavsky
Hey David, i got it working, thanks for the help.
Suhail
Great :-) If my answer helped it'd be nice to have an upvote
David Zaslavsky
A: 

Maybie the minimal http cgi upload recipe and it's comments are helpful for you.

Joschua
A: 

Hey David i got it working, i did it this way:

filename = request.FILES['fname']
destination = open('%s/%s'%(/tmp/,fileName), 'wb+')
for chunk in filename.chunks():
            destination.write(chunk)
destination.close()

file = open('%s/%s'%(/tmp/,fileName),"rb").read()

Thanks for the help guys.

Suhail
It's fine to post your code as an answer if nobody else's answer is sufficient, but you probably shouldn't write it as if you're responding to someone else.
David Zaslavsky