返回 zip 以从 django 中的视图下载

发布于 2024-11-05 21:24:06 字数 812 浏览 0 评论 0原文

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

我应该如何从视图中返回它?

我尝试了下面的代码,但我在浏览器中收到了某种警报,其中包含我的 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

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

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.

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

北城半夏 2024-11-12 21:24:06

您应该告诉浏览器将响应视为文件附件。

来自 docs,你应该这样做:

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

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'
も让我眼熟你 2024-11-12 21:24:06

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

Here is a link to actual working code for building a ZipFile in memory and returning it to the user as a file to download: django-rosetta's view.py

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文