Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Python

Cách hiển thị hộp thoại tải file (File Download Dialog) trong Python CGI?

Đôi khi muốn cho user click link và hiện hộp thoại "File Download" thay vì hiển thị nội dung. Rất dễ đạt được qua HTTP header.

Ví dụ làm file FileName có thể tải xuống:

#!/usr/bin/python
# HTTP Header
print "Content-Type:application/octet-stream; name=\"FileName\"\r\n"
print "Content-Disposition: attachment; filename=\"FileName\"\r\n\n"
# Nội dung file thực tế
fo = open("foo.txt", "rb")
str = fo.read()
print str
fo.close()