2016-11-17 62 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