Hubro
Hubro

Reputation: 59383

How does the cgi.FieldStorage class work with file uploads?

The entire question is pretty much in the title.

The only documentation I can find on the class is the very sparing cgi documentation and it doesn't mention in the least how the class receives the file, how it's stored, what functions it supports etc.

I'm very interested in where the uploaded file is stored. Clearly it's not in memory, since Bottle mentions the FileStorage.read() function is dangerous on large files. If it's placed on the disk, I would like to move it to a permanent location without having to read through it in Python copy it bit by bit to a new location.

But I have no clue where to begin due to the poor documentation of the class. Any ideas?

Upvotes: 2

Views: 2034

Answers (3)

I hope this could help:

http://epydoc.sourceforge.net/stdlib/cgi.FieldStorage-class.html

cgi.FieldStorage() has

  • a "filename",
  • a "value" - the file itself,
  • a "file" and
  • a "type"

And something else... you could read in the doc.

Here is my code:

f_sd=open(tempfilesd,'r+b')
newdata_sd = cgi.FieldStorage()
newdata_sd.filename='sdfile.jpg'
newdata_sd.name='file'
newdata_sd.file=f_sd
form.vars.file = newdata_sd

Upvotes: 0

Richard Galka
Richard Galka

Reputation: 51

A little late, but looking into this myself:

It all comes down to the 'make_file' method in cgi.py:

def make_file(self, binary=None):
    import tempfile
    return tempfile.TemporaryFile("w+b")

The tempfile docs ( http://docs.python.org/2/library/tempfile.html ) identify that the file is created in a default directory chosen from a platform-dependent list, but that the user can control the directory location by setting one of the environment variables: TMPDIR, TEMP or TMP.

Please also note from the documentation:

Under Unix, the directory entry for the file is removed immediately after the file is created. Other platforms do not support this; your code should not rely on a temporary file created using this function having or not having a visible name in the file system.

Hope this helps.

Upvotes: 2

moschlar
moschlar

Reputation: 1336

The FieldStorage.file attribute is actually not a file but a cStringIO object, which is described as a memory file on the docs: http://docs.python.org/library/stringio.html

Maybe this can help you a bit.

Upvotes: -1

Related Questions