views:

509

answers:

2

hi, I'm running python 2.4 from cgi and I'm trying to upload to a cloud service using a python api. In php, the $_FILE array contains a "tmp" element which is where the file lives until you place it where you want it. What's the equivalent in python?

if I do this

fileitem = form['file']

fileitem.filename is the name of the file

if i print fileitem, the array simply contains the file name and what looks to be the file itself.

I am trying to stream things and it requires the tmp location when using the php api.

+1  A: 

Here's a code snippet taken from my site:

h = open("user_uploaded_file", "wb")
while 1:
    data = form["file"].file.read(4096)
    if not data:
        break
    h.write(data)
h.close()

Hope this helps.

Helgi
+1  A: 

The file is a real file, but the cgi.FieldStorage unlinked it as soon as it was created so that it would exist only as long as you keep it open, and no longer has a real path on the file system.

You can, however, change this...

You can extend the cgi.FieldStorage and replace the make_file method to place the file wherever you want:

import os
import cgi

class MyFieldStorage(cgi.FieldStorage):
    def make_file(self, binary=None):
        return open(os.path.join('/tmp', self.filename), 'wb')

You must also keep in mind that the FieldStorage object only creates a real file if it recieves more than 1000B (otherwise it is a cStringIO.StringIO)

EDIT: The cgi module actually makes the file with the tempfile module, so check that out if you want lots of gooey details.

Mike Boers
I'm not necessarily looking to change the way it deals with files, but when I try to write the contents of file in chunks it works fine for small text files, but any video or images are uploaded corrupt. I thought this might be solved by streaming it as the php api does
sean smith
If you want to stream it, you can return an object with a write function to take the data from the Field Storage as it receives it. This is what I am doing to get AJAX upload progress info back to the browser for one of my projects.
Mike Boers
i'm trying to get files onto a cdn cloud container, so "stream" has to happen according to their api. I like your suggestion to override FieldStorage, but it's not working for me right now. I'm sort of new to python and might be missing something simple.
sean smith