Transfer Text File in Web Server to Client
I try to use the following script to transfer a text file located in web server, to client (The text file is in UTF-16).
import cgi
print "Content-Type: text/plain"
print "Content-Disposition: attachment; filename=TEST.txt"
print
filename = "C:\\TEST.TXT"
f = open(filename, 'r')
for line in f:
print line
However, when I open up the downloaded file, the file is all having weird characters. I try to use rb
flag, it doesn't either.
Is there anything I had missed out? What I wish is, the file (TEST.TXT) downloaded by the client by making query to the above script, will be exactly same as the one in server.
I als开发者_高级运维o try to specific the encoding explicitly.
import cgi
print "Content-Type: text/plain; charset=UTF-16"
print "Content-Disposition: attachment; filename=TEST.txt"
print
filename = "C:\\TEST.TXT"
f = open(filename, 'r')
for line in f:
print line.encode('utf-16')
That doesn't work either.
Original File on Server
Downloaded File
I will have the original text file being posted here in case you are interested to experiment it out.
First, you should specify the file encoding in your Content-Type
header:
print "Content-Type: text/plain; charset=UTF-16"
print "Content-Disposition: attachment; filename=TEST.txt"
print
Then, you have to actually encode the lines in UTF-16 when sending them to the client:
print "\xff\xfe", # send UTF-16 big-endian BOM
for line in f:
print line.encode("utf-16be")
Just ignore the text encoding, and transfer byte-to-byte to client with 0 modification.
#!c:/Python27/python.exe -u
import sys
print "Content-Type: text/plain;"
print "Content-Disposition: attachment; filename=TEST.txt"
print
filename = "C:\\TEST.TXT"
f = open(filename, 'rb')
while True:
data = f.read(4096)
sys.stdout.write(data)
if not data:
break
精彩评论