Django 的响应 ZIP 文件

E. *_*ozz 8 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
Run Code Online (Sandbox Code Playgroud)

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

Bor*_*rut 12

如果您使用的是 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
Run Code Online (Sandbox Code Playgroud)

那是在不保存文件的情况下。下载的文件直接转到io.

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

response = HttpResponse(open('path/to/file', 'rb').read())
Run Code Online (Sandbox Code Playgroud)