我尝试从 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
Run Code Online (Sandbox Code Playgroud)
当我将文件保存到 tmp 文件夹时 - 没关系,我可以提取它。但是,当我响应此文件时,如果我尝试在 Atom 编辑器中打开(仅用于测试),我会在 MacOS 上收到“错误 1/2/21”或意外的 EOF。我还使用了 StringIO 而不是保存 …