【问题标题】:Response ZIP file by DjangoDjango的响应ZIP文件
【发布时间】:2019-01-22 22:14:00
【问题描述】:

我尝试从 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 上收到“错误 1/2/21”或 Unexpected EOF。 我也使用了StringIO而不是保存zip文件,但它不影响结果。

【问题讨论】:

    标签: python django zip


    【解决方案1】:

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

    【讨论】:

    • 正如我上面提到的,我已经使用 io 来创建文件。但问题在于响应文件,而不是创建的文件。
    • @E.Mozz:要返回文件,请将 .read() 添加到 open(),open('tmp/album.zip', 'rb').read())
    • 它没有改变任何东西,尝试打开存档时仍然出错。
    • 简单且最佳的解决方案。非常感谢。
    猜你喜欢
    • 2018-11-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-02-05
    • 1970-01-01
    • 2019-12-11
    • 2020-06-21
    • 2021-10-02
    相关资源
    最近更新 更多