Python CGI文件下载名称更改

Python CGI文件下载名称更改,python,cgi,Python,Cgi,我尝试使用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

我尝试使用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
#HTTP头
fileName='downloadedFile'
打印“内容类型:应用程序/八位字节流;名称=\%s\”\r\n“%fileName;
打印“内容处置:附件;文件名=\%s\”\r\n\n“%filename;
数据=“”
尝试:
以open(完整路径,'rb')作为fo:
data=fo.read();
打印数据
例外情况除外,如e:
打印“内容类型:text/html\r\n\r\n”
打印“
异常:” 打印e

文件以名称
download.py下载,而不是
downloadedFile
。如何将下载的文件名设置为
downloaddedfile

您是从PHP复制的吗?(PHP使用
,但Python不需要它)

您的
\n
太多了。在Python中,打印自动添加
\n

在第一个标题(第一个
print
)之后,您有两个
\n\n
(由
print
添加了“\n”),所以在标题之后有一个空行,表示标题的结尾。所以第二行的名字并不是作为标题,而是作为身体的一部分

#!/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

你是从PHP复制的吗?(PHP使用
,但Python不需要它)

您的
\n
太多了。在Python中,打印自动添加
\n

在第一个标题(第一个
print
)之后,您有两个
\n\n
(由
print
添加了“\n”),所以在标题之后有一个空行,表示标题的结尾。所以第二行的名字并不是作为标题,而是作为身体的一部分

#!/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

非常感谢,非常感谢