Để tải lên tệp, biểu mẫu HTML phải có thuộc tính enctype thiết lập thành multipart/form-data. Thẻ input với loại file tạo nút "Duyệt".
<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>
Đầu ra
Kết quả của mã này là biểu mẫu sau:

Ví dụ trên đã bị vô hiệu hóa cố ý để tránh mọi người tải tệp lên máy chủ của chúng tôi, nhưng bạn có thể thử mã trên với máy chủ của mình.
Dưới đây là script save_file.py để xử lý tải lên tệp:
#!/usr/bin/python
import cgi, os
import cgitb; cgitb.enable()
form = cgi.FieldStorage()
# Lấy tên tệp tại đây
fileitem = form['filename']
# Kiểm tra xem tệp có được tải lên không
if fileitem.filename:
# Loại bỏ đường dẫn đầu để tránh tấn công duyệt thư mục
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
%s
""" % (message,)
Nếu bạn chạy script trên trên Unix/Linux, bạn cần thay thế phân cách tệp như sau, ngược lại trên máy Windows câu lệnh open() trên sẽ hoạt động tốt.
fn = os.path.basename(fileitem.filename.replace("\\", "/"))