Django的响应ZIP文件

时间:2019-01-22 22:14:00

标签: python django zip

我尝试从URL下载img,将其添加到zip存档中,然后通过Django HttpResponse响应此存档。

import os
import requests
import zipfile
from django.http import HttpResponse

url = 'http://some.link/img.jpg' 
file = requests.get(url)
data = file.content
rf = open('tmp/pic1.jpg', 'wb')
rf.write(data)
rf.close()
zipf = zipfile.ZipFile('tmp/album.zip', 'w') # This file is ok
filename = os.path.basename(os.path.normpath('tmp/pic1.jpg'))
zipf.write('tmp/pic1.jpg', filename)
zipf.close()
resp = HttpResponse(open('tmp/album.zip', 'rb'))
resp['Content-Disposition'] = 'attachment; filename=album.zip'
resp['Content-Type'] = 'application/zip'
return resp # Got corrupted zip file

当我将文件保存到tmp文件夹中时-可以,我可以将其解压缩。 但是,当我响应此文件时,如果我尝试在Atom编辑器中打开(仅用于测试),则会在MacOS或意外的EOF上收到“错误1/2/21”。 我还使用StringIO而不是保存zip文件,但这不会影响结果。

1 个答案:

答案 0 :(得分:0)

如果您使用的是Python 3,则可以这样做:

import os, io, zipfile, requests
from django.http import HttpResponse

# Get file
url = 'https://some.link/img.jpg'
response = requests.get(url)
# Get filename from url
filename = os.path.split(url)[1]
# Create zip
buffer = io.BytesIO()
zip_file = zipfile.ZipFile(buffer, 'w')
zip_file.writestr(filename, response.content)
zip_file.close()
# Return zip
response = HttpResponse(buffer.getvalue())
response['Content-Type'] = 'application/x-zip-compressed'
response['Content-Disposition'] = 'attachment; filename=album.zip'

return response

那是不保存文件的。下载的文件直接进入io

要响应保存的文件,请使用以下语法:

response = HttpResponse(open('path/to/file', 'rb').read())