简体   繁体   English

从django中查看返回zip以供下载

[英]returning zip for download from view in django

I try to download a zip file in my Django application. 我尝试在我的Django应用程序中下载一个zip文件。

How should I return it from the view? 我应该如何从视图中返回它?

I tried the code below, but I get some kind of alert in the browser with the content of the file inside my zip. 我尝试了下面的代码,但是我在浏览器中得到了一些警报,其中包含我的zip文件内容。

What am I doing wrong? 我究竟做错了什么?

def download_logs(request):
    date = datetime.datetime.now().__str__().replace(" ", "_").split(".")[0]
    os.system("df -h . > /tmp/disk_space")
    response = HttpResponse(mimetype='application/zip')
    response['Content-Disposition'] = 'filename=logs_%s.zip' % date

    files = []
    files.append("/tmp/disk_space")
    buffer = StringIO()
    zip = zipfile.ZipFile(buffer, "w", zipfile.ZIP_DEFLATED)
    for name in files:
        file = open(name, "r")
        zip.writestr(name, file.read())
        file.close()
    zip.close()
    buffer.flush()

    ret_zip = buffer.getvalue()
    buffer.close()
    response.write(ret_zip)
    return response

You should tell the browser to treat the response as a file attachment. 您应该告诉浏览器将响应视为文件附件。

From the docs , you should do something like: 文档中 ,您应该执行以下操作:

>> response = HttpResponse(my_data, mimetype='application/vnd.ms-excel')
>>> response['Content-Disposition'] = 'attachment; filename=foo.xls'

这是一个实际工作代码的链接,用于在内存中构建ZipFile并将其作为要下载的文件返回给用户: django-rosetta的view.py

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

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