我正在遵循这个解决方案(在 Django 中提供动态生成的 ZIP 档案)来提供来自 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'
谢谢