我对Django有点陌生,所以请容忍我。
我使用来自这里的zip流,并有一个Django视图,该视图返回所有文件附件的压缩文件,这些附件都托管在S3上。但是当我下载的时候,压缩文件都被破坏了,也就是说,我不能打开它们。我试过用unzip -t验证这些文件,但是错误并不是很有帮助。
file_paths = [fa.file.url for fa in file_attachments.all()]
zf = zipstream.ZipFile(mode='w', compression=zipstream.ZIP_DEFLATED)
zip_subdir = "Attachments-%s" % (request_id)
for file_path in file_paths:
file_dir, file_name = os.path.split(file_path)
zf.writestr(file_name, urllib.urlopen(file_path).read())
zip_filename = "%s.zip" % (zip_subdir)
response = StreamingHttpResponse(zf, mimetype='application/zip')
response['Content-Disposition'] = \
'attachment; filename={}'.format(zip_filename)
return response有什么想法吗?
解决了。
s = StringIO.StringIO()
with zipstream.ZipFile(s, mode='w', compression=zipstream.ZIP_DEFLATED) as zf:
#could fail on url open.
for file_path in file_paths:
file_dir, file_name = os.path.split(file_path)
try:
file_contents = urllib.urlopen(file_path).read()
zf.writestr(file_name, file_contents)
except IOError: #connection cannot be made
logging.error()
response = StreamingHttpResponse(s.getvalue(), mimetype='application/octet-stream')
response['Content-Disposition'] = \
'attachment; filename={}'.format("%s" % (request_id))
return response发布于 2014-10-15 17:23:37
当您写完ZipFile时,应该关闭它。否则,引用文档的话,“基本记录将不会被写入”,直到你这样做。
最干净的方法是使用with语句:
with zipstream.ZipFile(mode='w', compression=zipstream.ZIP_DEFLATED) as zf:
# ...write to zf...https://stackoverflow.com/questions/26388324
复制相似问题