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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12881294/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 12:05:23  来源:igfitidea点击:

Django - Create A Zip of Multiple Files and Make It Downloadable

pythondjangofile

提问by yretuta

Possible Duplicate:
Serving dynamically generated ZIP archives in Django

可能的重复:
在 Django 中提供动态生成的 ZIP 档案

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

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

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

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

and this answer:

和这个答案:

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.

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

Thank in advance!

预先感谢!

采纳答案by dbr

I've posted this on the duplicate questionwhich 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

回答by Nate Gentile

So as I understand your problem is not how to generate dynamically this file, but creating a link for people to download it...

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

What I suggest is the following:

我的建议如下:

0) Create a model for your file, if you want to generate it dynamically don't use the FileField, but just the info you need for generating this file:

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

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

1) Create and store your Zip. This step is important, you create your zip in memory, and then cast it to assign it to the FileField:

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) Create a url, for example get a number matching the id, you can also use a slugfield (this)

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

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

3) Now the view, this view will return the file matching the id passed in the url, you can also use a slug sending the text instead of the id, and make the get filtering by your slugfield.

3) 现在是视图,该视图将返回与 url 中传递的 id 匹配的文件,您也可以使用发送文本而不是 id 的 slug,并通过您的 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