CGI File Upload

Bill Seitz fluxent at
Wed Dec 6 19:27:38 CET 2000

In article <90j10o$5p5$1 at>,
  Bill Seitz <fluxent at> wrote:
> In article <8u7fn7$jpf$1 at>,
>   "Pete Shinners" <pete at> wrote:
> > "Simon Faulkner" <news at> wrote
> > > I would like users to be able to upload .jpeg files via a web page
> > > <input type=file>
> > >
> > > What python code do I need to be able to save the file to a
> directory
> > > on the hard disk?
> >
> > i have some code that does this.. you'll probably want to clean
> > it to suit your own purposes, but here it is. at some point i
> > wanted to add PIL support to resize the images to a certain
> > resolution and convert them to be JPG, but that day hasn't come
> > yet... heh. note it also allows the user to save a comment as a
> > .TXT file. anyways, you can use it as a start for whatever you want
> Hmm, this works for me with text data (though the file length is
> slightly different: maybe line-end changes from Win to *nix?). With
> binary it's totally off. Uploading a JPEG I consistently only get 109
> bytes written to the file system. With GIFs I consistently get ~500
> bytes (but not always exactly the same number). With an MsWord file I
> get a bigger file written, but still not the whole thing (60kb out of
> 75kb).
> What do I do next?

Some recommendations were made by Barry Pederson
(bpederson at I didn't need them since setting the mode
was sufficient, but wanted to share them anyway, since others might
find them necessary/helpful...

I was recently working on a CGI that did file uploads under
Win32/Apache, and found these 3 things needed adjusting for it to work

1. Make sure you use a fixed version of the module.  The
the version in 2.0 or earlier reads the entire file upload
into memory, which is impractical in the case of multi-megabyte
uploads.  It's supposed to be fixed in Python 2.1, but
you can fix the 2.0 or earlier version yourself by commenting
out the 3 or so lines that call "self.lines.append()"

2. If on Win32, be sure to either arrange to run python with the
"-u" parameter, or with the PYTHONUNBUFFERED environment variable
set to 1.  Otherwise the uploaded files will be truncated if
characters such as Ctrl-Z appear in them.

This can be done in the Apache config with the SetEnv directive:


right after the ScriptAlias directive for example.

3. In addition to the fix listed above, you also will need a tweaked
version of (which is called by, that puts a
try/except wrapper around the one call to tell() that doesn't
already have one.  It's been submitted as a bug to the Python guys,
and Guido says he's made my suggested fix, so it should also be in
Python 2.1.

Sent via
Before you buy.

More information about the Python-list mailing list