我正在用Python和CGI编写一个小型网站,用户可以在其中上传zip文件并下载其他用户上传的文件。目前,我可以正确上传zip文件,但是在将文件正确发送给用户时遇到了一些麻烦。我的第一种方法是:
file = open('../../data/code/' + filename + '.zip','rb')
print("Content-type: application/octet-stream")
print("Content-Disposition: filename=%s.zip" %(filename))
print(file.read())
file.close()
但是很快我意识到我必须以二进制形式发送文件,所以我尝试了:
print("Content-type: application/octet-stream")
print("Content-Disposition: filename=%s.zip" %(filename))
print('Content-transfer-encoding: base64\r')
print( base64.b64encode(file.read()).decode(encoding='UTF-8') )
以及它的不同变体。只是行不通;Apache引发“来自脚本的标头格式错误”错误,因此我想我应该以其他方式对文件进行编码。
您需要在标题后打印一个空行,并且Content-disposition标题缺少类型(attachment
):
print("Content-type: application/octet-stream")
print("Content-Disposition: attachment; filename=%s.zip" %(filename))
print()
您可能还想使用一种更有效的方法来上传结果文件。用于shutil.copyfileobj()
将数据复制到sys.stdout.buffer
:
from shutil import copyfileobj
import sys
print("Content-type: application/octet-stream")
print("Content-Disposition: attachment; filename=%s.zip" %(filename))
print()
with open('../../data/code/' + filename + '.zip','rb') as zipfile:
copyfileobj(zipfile, sys.stdout.buffer)
print()
在任何情况下都不应使用二进制数据;您得到的只是b'...'
字节文字语法。该sys.stdout.buffer
对象是基础二进制I / O缓冲区,直接将二进制数据复制到该缓冲区。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句