Để tải tệp lên, biểu mẫu HTML phải có thuộc tính enctype được đặt thành nhiều phần / biểu mẫu-dữ liệu . Thẻ đầu vào có loại tệp sẽ tạo nút "Duyệt qua".
<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à dạng sau -
Ví dụ trên đã bị vô hiệu hóa có chủ ý để lưu những người tải tệp lên trê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.
Đây là tập lệnh save_file.py để xử lý tải lên tệp -
#!/usr/bin/python
import cgi, os
import cgitb; cgitb.enable()
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
<html>
<body>
<p>%s</p>
</body>
</html>
""" % (message,) Nếu bạn chạy tập lệnh trên trên Unix / Linux, thì bạn cần chú ý thay thế dấu phân tách tệp như sau, nếu không trên máy windows của bạn ở trên câu lệnh open () sẽ hoạt động tốt.
fn = os.path.basename(fileitem.filename.replace("\\", "/" ))