6.4. File uploads
To upload a file from the client to the server, the input tag must have the type "file". For instance, the html form will look like this :
<FORM ENCTYPE="multipart/form-data" ACTION="fileUpload.py" METHOD=POST> File to process: <INPUT NAME="myfile" TYPE="file"> <INPUT TYPE="submit" VALUE="Send File"> </FORM>
The script which has to handle the file upload will use the variable
REQUEST['myfile']
or _myfile
, which is an instance of the
class FieldStorage
in the built-in cgi
module.
This object has two useful attributes :
filename
: the name of the filefile
: a file-like object from which you can read the file content
For instance if you want to store the file in the server's file system, with the same name as the original file :
import os f = _myfile.file # file-like object dest_name = os.path.basename(_myfile.filename) out = open(dest_name,'wb') # copy file import shutil shutil.copyfileobj(f,out) out.close()