关于python:Django的响应ZIP文件

Response ZIP file by Django

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
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 上得到"错误 1/2/21"或 Unexpected EOF。
我也使用了 StringIO 而不是保存 zip 文件,但它不影响结果。


如果你使用的是 Python 3,你会这样做:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
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.

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

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