説明
サーバにあるファイルをクライアント(ブラウザ)にダウンロードするメソッドです。"Content-Disposition: attachment"により、ブラウザ側ではダウンロードダイアログが表示され、「開く」か「保存」するかをユーザが選択することができます。
プラットフォームがWindowsの場合は、入出力デバイスのテキスト/バイナリの区別があるので、
msvcrt.setmode(sys.stdout.fileno(), os.O_BINARY)
として、標準出力デバイスをバイナリモードにしています。
※クライアントから、ダウンロード要求があった場合にサーバ側で行う処理です。
ソース
0
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
| | import sys
import os
class DownloadFile:
def do(self, file):
sys.stdout.write("Content-Type: application/octet-stream\n")
sys.stdout.write("Content-Disposition: attachment; filename=\"" + os.path.basename(file) + "\"\n")
sys.stdout.write("Content-Length: " + str(os.path.getsize(file)) + "\n")
sys.stdout.write("Expires: 0\n")
sys.stdout.write("Cache-Control: must-revalidate, post-check=0,pre-check=0\n")
sys.stdout.write("Pragma: private\n")
sys.stdout.write("\n")
if sys.platform == "win32":
import msvcrt
msvcrt.setmode(sys.stdout.fileno(), os.O_BINARY)
myfile = open(file,'rb')
sys.stdout.write(myfile.read())
myfile.close()
r = DownloadFile()
r.do('c:\\okinawa.csv')
|