Django - 创建一个多个文件的zip并使其可下载 [英] Django - Create A Zip of Multiple Files and Make It Downloadable

查看:541
本文介绍了Django - 创建一个多个文件的zip并使其可下载的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:

在Django中提供动态生成的ZIP档案





(Feel free to point me to any potential duplicates if I have missed them)

我已经看过这个代码段:
http://djangosnippets.org/snippets/365/

I have looked at this snippet: http://djangosnippets.org/snippets/365/

和这个答案:

但我不知道我可以如何调整他们以满足我的需要:我希望多个文件被压缩,存档可通过链接下载(或通过视图动态生成)。我是Python和Django的新手,所以我不知道该怎么做。

but I wonder how I can tweak them to suit my need: I want multiple files to be zipped and the archive available as a download via a link (or dynamically generated via a view). I am new to Python and Django so I don't know how to go about it.

提前感谢

推荐答案

我已经发布在重复的问题,Willy链接到,但是由于与赏金有关的问题不能被视为重复的,所以也可以将其复制到这里:

I've posted this on the duplicate question which Willy linked to, but since questions with a bounty cannot be closed as a duplicate, might as well copy it here too:

import os
import zipfile
import StringIO

from django.http import HttpResponse


def getfiles(request):
    # Files (local path) to put in the .zip
    # FIXME: Change this (get paths from DB etc)
    filenames = ["/tmp/file1.txt", "/tmp/file2.txt"]

    # Folder name in ZIP archive which contains the above files
    # E.g [thearchive.zip]/somefiles/file2.txt
    # FIXME: Set this to something better
    zip_subdir = "somefiles"
    zip_filename = "%s.zip" % zip_subdir

    # Open StringIO to grab in-memory ZIP contents
    s = StringIO.StringIO()

    # The zip compressor
    zf = zipfile.ZipFile(s, "w")

    for fpath in filenames:
        # Calculate path for file in zip
        fdir, fname = os.path.split(fpath)
        zip_path = os.path.join(zip_subdir, fname)

        # Add file, at correct path
        zf.write(fpath, zip_path)

    # Must close zip for all contents to be written
    zf.close()

    # Grab ZIP file from in-memory, make response with correct MIME-type
    resp = HttpResponse(s.getvalue(), mimetype = "application/x-zip-compressed")
    # ..and correct content-disposition
    resp['Content-Disposition'] = 'attachment; filename=%s' % zip_filename

    return resp

这篇关于Django - 创建一个多个文件的zip并使其可下载的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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