Computer >> 컴퓨터 >  >> 프로그램 작성 >> Python

Python CGI 프로그래밍에서 파일 다운로드 대화 상자를 표시하는 방법은 무엇입니까?


때로는 사용자가 링크를 클릭할 수 있는 옵션을 제공하고 실제 콘텐츠를 표시하는 대신 사용자에게 "파일 다운로드" 대화 상자를 표시할 수 있습니다. 이것은 매우 쉽고 HTTP 헤더를 통해 달성할 수 있습니다.

예를 들어, 주어진 링크에서 FileName 파일을 다운로드 가능하게 만들려면 해당 구문은 다음과 같습니다 -

#!/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 opend file
fo.close()