Python CGI文件下载名称更改
Python CGI filedownload name change
我正在尝试使用 CGI 下载文件,它工作正常,但下载的文件具有 python 脚本文件的名称。
我的代码:
#Source file name : download.py
#HTTP Header
fileName='downloadedFile'
print "Content-Type:application/octet-stream; name=\"%s\"\r\n" %fileName;
print "Content-Disposition: attachment; filename=\"%s\"\r\n\n" %fileName;
data= ''
try:
with open(fullPath,'rb') as fo:
data = fo.read();
print data
except Exception as e:
print "Content-type:text/html\r\n\r\n"
print '<br>Exception :'
print e
下载的文件名称为 download.py
而不是 downloadedFile
。如何将下载的文件名设置为downloadedFile
?
你是从 PHP 复制的吗? (PHP 使用 ;
但 Python 不需要它)
你有太多\n
。在 Python print
中自动添加 \n
。
在第一个 header(第一个 print
)之后你有两个 \n\n
(print
添加了 '\n')所以在 header 你之后有空行,表示 headers 结束。所以带有名字的第二行没有被威胁为 header 而是作为 body.
的一部分
#!/usr/bin/env python
import os
import sys
fullpath = 'images/normal.png'
filename = 'hello_world.png'
print 'Content-Type: application/octet-stream; name="%s"' % filename
print 'Content-Disposition: attachment; filename="%s"' % filename
print "Content-Length: " + str(os.stat(fullpath).st_size)
print # empty line between headers and body
#sys.stdout.flush()
try:
with open(fullpath, 'rb') as fo:
print fo.read()
except Exception as e:
print 'Content-type:text/html'
print # empty line between headers and body
print 'Exception :', e
我正在尝试使用 CGI 下载文件,它工作正常,但下载的文件具有 python 脚本文件的名称。
我的代码:
#Source file name : download.py
#HTTP Header
fileName='downloadedFile'
print "Content-Type:application/octet-stream; name=\"%s\"\r\n" %fileName;
print "Content-Disposition: attachment; filename=\"%s\"\r\n\n" %fileName;
data= ''
try:
with open(fullPath,'rb') as fo:
data = fo.read();
print data
except Exception as e:
print "Content-type:text/html\r\n\r\n"
print '<br>Exception :'
print e
下载的文件名称为 download.py
而不是 downloadedFile
。如何将下载的文件名设置为downloadedFile
?
你是从 PHP 复制的吗? (PHP 使用 ;
但 Python 不需要它)
你有太多\n
。在 Python print
中自动添加 \n
。
在第一个 header(第一个 print
)之后你有两个 \n\n
(print
添加了 '\n')所以在 header 你之后有空行,表示 headers 结束。所以带有名字的第二行没有被威胁为 header 而是作为 body.
#!/usr/bin/env python
import os
import sys
fullpath = 'images/normal.png'
filename = 'hello_world.png'
print 'Content-Type: application/octet-stream; name="%s"' % filename
print 'Content-Disposition: attachment; filename="%s"' % filename
print "Content-Length: " + str(os.stat(fullpath).st_size)
print # empty line between headers and body
#sys.stdout.flush()
try:
with open(fullpath, 'rb') as fo:
print fo.read()
except Exception as e:
print 'Content-type:text/html'
print # empty line between headers and body
print 'Exception :', e