Question

I'm trying to detect whether an optional file has been uploaded or not when a cgi form has been submitted.

I've read here that I should be doing something like:

myfile = form["myfile"]
if myfile.file:
    # It's an uploaded file; save it to disk
    file = open('path_to_file','wb')
    file.write(myfile.file.read())
    file.close()

But this is not working for me. The file is always being written, whether it's been uploaded or not.

While with any other fields I can always use a default value to check it:

field = cgi.escape(data.getfirst('field','null'))

I can't see the approach to face this for files in the documentation. Any help there?

Thanks.

Was it helpful?

Solution

I tested with Firefox, and uploading a form with an empty file input results in the following post contents:

-----------------------------135438447855682763402193870
Content-Disposition: form-data; name="foo"; filename=""
Content-Type: application/octet-stream 

-----------------------------135438447855682763402193870--

Thus a zero-length field is uploaded. However no filename is set so test for the value of the filename attribute instead.

If a field represents an uploaded file, accessing the value via the value attribute or the getvalue() method reads the entire file in memory as a string. This may not be what you want. You can test for an uploaded file by testing either the filename attribute or the file attribute.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top