Lesson - 69 : Python Advanced - Python CGI Programming : File Upload Example

Published: 28 January 2018
on channel: Sada Learning Hub
1,420
12

Python CGI Programming : File Upload Example:
To upload a file, the HTML form must have the enctype attribute set to multipart/form-data. The input tag with the file type creates a "Browse" button.

<html>
<body>
<form enctype="multipart/form-data"
action="save_file.py" method="post">
<p>File: <input type="file" name="filename" /></p>
<p><input type="submit" value="Upload" /></p>
</form>
</body>
</html>

Above example has been disabled intentionally to save
people uploading file on our server, but you can try
above code with your server.
Here is the script save_file.py to handle file upload −

form = cgi.FieldStorage()
Get filename here.
fileitem = form['filename']
Test if the file was uploaded
if fileitem.filename:
strip leading path from file name to avoid
directory traversal attacks
fn = os.path.basename(fileitem.filename)
open('/tmp/' + fn, 'wb').write(fileitem.file.read())
message = 'The file "' + fn + '" was uploaded successfully'
else:
message = 'No file was uploaded'
print """\
Content-Type: text/html\n

Sample Projects : https://github.com/SadaLearningHub1/P...


On this page of the site you can watch the video online Lesson - 69 : Python Advanced - Python CGI Programming : File Upload Example with a duration of hours minute second in good quality, which was uploaded by the user Sada Learning Hub 28 January 2018, share the link with friends and acquaintances, this video has already been watched 1,420 times on youtube and it was liked by 12 viewers. Enjoy your viewing!