How To Deploy Zip Files (or Other Binaries) Trough Cgi In Python?
I'm coding a small website with Python and CGI where users can upload zip files and download files uploaded by other users. Currently I'm able to upload correctly the zip's, but I
Solution 1:
You need to print an empty line after the headers, and you Content-disposition header is missing the type (attachment
):
print("Content-type: application/octet-stream")
print("Content-Disposition: attachment; filename=%s.zip" %(filename))
print()
You may also want to use a more efficient method of uploading the resulting file; use shutil.copyfileobj()
to copy the data to sys.stdout.buffer
:
from shutil import copyfileobj
import sys
print("Content-type: application/octet-stream")
print("Content-Disposition: attachment; filename=%s.zip" %(filename))
print()
withopen('../../data/code/' + filename + '.zip','rb') as zipfile:
copyfileobj(zipfile, sys.stdout.buffer)
You should not use print()
for binary data in any case; all you get is b'...'
byte literal syntax. The sys.stdout.buffer
object is the underlying binary I/O buffer, copy binary data directly to that.
Solution 2:
The header is malformed because, for some reason, Python sends it after sending the file.
What you need to do is flush stdout right after the header:
sys.stdout.flush()
Then put the file copy
Post a Comment for "How To Deploy Zip Files (or Other Binaries) Trough Cgi In Python?"