Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

วิธีแสดง File Download Dialog Box ใน Python CGI Programming

บางครั้งต้องการให้ User คลิก Link แล้วแสดง Dialog Box "File Download" แทนการแสดงเนื้อหาจริง ทำได้ง่ายผ่าน HTTP Header

ตัวอย่าง หากต้องการทำให้ FileName ดาวน์โหลดได้จาก Link ไวยากรณ์คือ -

#!/usr/bin/python
# HTTP Header
print "Content-Type:application/octet-stream; name = \"FileName\"\r\n"
print "Content-Disposition: attachment; filename = \"FileName\"\r\n\n"
# Actual File Content will go here
fo = open("foo.txt", "rb")
str = fo.read()
print str
# Close opened file
fo.close()