2016-11-17 60 views
-1

我正在尝试使用CGI进行文件下载,它的工作正常,下载的文件具有python脚本文件的名称。Python CGI文档下载名称更改

我的代码:

#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

回答

1

你从PHP复制这个吗? (PHP使用;但Python不需要它)

你有太多的\n。在Python print中自动添加\n

第一报头(第一print)之后有两个\n\n(与“\ n”由print加入),这样报头之后你必须空行,这意味着头的端部。所以名称的第二行不是作为头部而是作为正文的一部分。

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

非常感谢你Faras :) – Kajal