繁体   English   中英

Django的响应ZIP文件

[英]Response ZIP file by Django

我尝试从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文件,但是它不会影响结果。

如果您使用的是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())

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM