INPUT TYPE=file in HTML
Richard van de Stadt
stadt at cs.utwente.nl
Fri Jul 14 05:39:22 EDT 2000
Jocelyn Paine wrote:
>
> Hi,
>
> I've been trying to read files uploaded from an HTML <INPUT TYPE=FILE>
> field using the CGI module. Are there known problems with this? The
> documentation says that if we take the value attribute of the form fields
> structure, it returns the entire contents of the file as a string. The
> file attribute returns a pointer to the file. But when I try this, I seem
> to get the filename as the value attribute, and nothing as the file
> attribute.
>
> The field is inside a form whose HTML arguments are just ACTION and
> METHOD, nothing else. The field has a TYPE argument whose value is "file",
> and a NAME attribute. And this combination of field and form works OK if I
> use it to pload a file to a Perl CGI.
If you use these on your webform:
<form enctype="multipart/form-data"
method="post"
action="/cgi-bin/yourScript.py">
<input name="theFile" type="file" size=40>
<input type="submit" value="Upload">
</form>
Then, in yourScript.py, you can get the filename and contents by using this:
import cgi
aForm = cgi.FieldStorage()
fname = aForm["theFile"].filename #(name at the client's side!)
fcontents = aForm["theFile"].value #(as a string)
There are more fields you can use. See cgi.py, which lists them.
Note: Apparently, the cgi.FieldStorage() uses some location to store
temporary results. If there is not enough disk space available at that
location ('/usr/tmp' or '/tmp', by default), it won't work, but you get
no error message. At least this was the case when I started using Python,
with release 1.4, where I could not catch this error. Since then, I assign
to os.environ['TMPDIR'] the name a directory of which I am sure that it
contains enough space to handle the files that are going to be uploaded.
Richard.
More information about the Python-list
mailing list