从django的视图返回zip下载 [英] returning zip for download from view in django

查看:76
本文介绍了从django的视图返回zip下载的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试在我的Django应用程序中下载zip文件。

I try to download a zip file in my Django application.

如何从视图中返回?

我尝试过下面的代码,但是在浏览器中,我的邮件内容就是文件内容。

I tried the code below, but I get some kind of alert in the browser with the content of the file inside my zip.

我做错了什么?

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.

docs ,您应该执行以下操作:

From the docs, you should do something like:

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

这篇关于从django的视图返回zip下载的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆