Kajal Kajal - 21 days ago 6
Python Question

Python CGI filedownload name change

I was trying to do file download using CGI, It's works fine excpt the downloaded file has the name of the python script file.

My code :

#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


The file downloads with a name
download.py
instead of
downloadedFile
. How can I set the downloaded file name to
downloadedFile
?

Answer

Did you copy this from PHP ? (PHP uses ; but Python doesn't need it)

You have too many \n. In Python print adds \n automatically.

After first header (first print) you had two \n\n (with '\n' added by print) so after header you had empty line which means end of headers. So second line with name wasn't threated as header but as part of 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