【问题标题】:Django - Create A Zip of Multiple Files and Make It Downloadable [duplicate]Django - 创建多个文件的 Zip 并使其可下载 [重复]
【发布时间】:2012-10-04 13:56:47
【问题描述】:

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

(如果我错过了任何可能的重复项,请随时指出我)

我看过这个sn-p: http://djangosnippets.org/snippets/365/

还有这个answer:

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

提前致谢!

【问题讨论】:

  • 查看 FileWrapper 的源代码,它似乎只接受一个文件。我不知道循环文件是否是 send_zipfile sn-p 的方法
  • 循环遍历文件并将它们写入存档在我的理论中是可行的。

标签: python django file


【解决方案1】:

我已经在 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

【讨论】:

  • 返回 Content-Disposition: attachment; filename="..." 标头 (specs here) 也很好,可以减少前端服务器错误配置干扰您的响应并将其全部发送到浏览器的可能性。
  • @MikhailSayapin 啊,有趣 - 添加了!
  • 请注意 mimetype 参数已被弃用,对于 Django 1.5+ 将其替换为 content_type
  • 如何添加内存文件? IE。上传的 Files 对象,来自数据库的文件对象,还是另一个 stringIO 文件?
  • 这适用于python2,对于Python3,请改用from io import BytesIO; s=BytesIO()。
【解决方案2】:

据我了解,您的问题不是如何动态生成此文件,而是创建一个供人们下载的链接...

我的建议如下:

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)创建一个url,例如获取一个与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

【讨论】:

  • 为什么不使用 ZipStored._meta.get_field_by_name('zip').upload_to 直接在文件系统上创建文件。为您的网络服务器节省大量内存和可能的 DOS 向量?
  • 我应该如何从 FileField 中获取文件名并将其与代码中的“文件名”变量一起使用?
  • 对于 Python3,使用 file_like = io.StringIO() 和 file_like.__sizeof__() 而不是 file_like.len
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-01-16
  • 2011-06-27
相关资源
最近更新 更多