Django - 创建多个文件的Zip并使其可下载

时间:2012-10-14 10:18:50

标签: python django file

  

可能重复:
  Serving dynamically generated ZIP archives in Django

(如果我错过了任何可能的副本,请随时指出我)

我看过这个片段: http://djangosnippets.org/snippets/365/

answer:

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

提前感谢!

2 个答案:

答案 0 :(得分:54)

我已将此发布在Willy链接的duplicate question上,但由于赏金问题不能作为副本关闭,因此也可以将其复制到此处:

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

答案 1 :(得分:4)

据我所知,你的问题不是如何动态生成这个文件,而是创建一个供人们下载的链接......

我建议如下:

0)为您的文件创建模型,如果您想动态生成它,请不要使用FileField,而只需要生成此文件所需的信息:

class ZipStored(models.Model):
    zip = FileField(upload_to="/choose/a/path/")

1)创建并存储您的Zip。这一步很重要,您在内存中创建zip,然后将其转换为将其分配给FileField:

function create_my_zip(request, [...]):
    [...]
    # This is a in-memory file
    file_like = StringIO.StringIO()
    # Create your zip, do all your stuff
    zf = zipfile.ZipFile(file_like, mode='w')
    [...]
    # Your zip is saved in this "file"
    zf.close()
    file_like.seek(0)
    # To store it we can use a InMemoryUploadedFile
    inMemory = InMemoryUploadedFile(file_like, None, "my_zip_%s" % filename, 'application/zip', file_like.len, None)
    zip = ZipStored(zip=inMemory)
    # Your zip will be stored!
    zip.save()
    # Notify the user the zip was created or whatever
    [...]

2)创建一个网址,例如获取一个与id匹配的数字,你也可以使用一个slugfield(this

url(r'^get_my_zip/(\d+)$', "zippyApp.views.get_zip")

3)现在看来,这个视图将返回与url中传递的id匹配的文件,你也可以使用slug发送文本而不是id,并通过你的slugfield进行get过滤。

function get_zip(request, id):
    myzip = ZipStored.object.get(pk = id)
    filename = myzip.zip.name.split('/')[-1]
    # You got the zip! Now, return it!
    response = HttpResponse(myzip.file, content_type='application/zip')
    response['Content-Disposition'] = 'attachment; filename=%s' % filename