提供Zip文件Django

时间:2013-10-30 19:17:01

标签: django

我正在按照此解决方案(Serving dynamically generated ZIP archives in Django)从django提供一些zip文件。

我们的想法是使用一些复选框从数据库中选择文件,但我试图让这个示例仅使用2个图像。

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 = ["/home/../image1.png", "/home/../image2.png"]

    # 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

我在views.py上写了getfile(request),然后从索引视图中调用

def index(request):

    if request.method == 'POST':  # If the form has been submitted...
        resp = getfiles(request)
        form = FilterForm(request.POST)  # A form bound to the POST data
        # do some validation and get latest_events from database

    context = {'latest_events_list': latest_events_list, 'form': form}
    return render(request, 'db_interface/index.html', context)

我知道调用了getfile()方法,因为如果我输入了不存在文件的名称,我得到了一个错误,但如果文件名是正确的,我也不会得到任何错误(我把完整的路径/ home / myuser /xxx/yyy/Project/app/static/app/image1.png)。

我尝试使用django服务器和我用于生产的apache2 / nginx服务器

我也尝试过使用content_type = 'application/force-download'

由于

0 个答案:

没有答案