【发布时间】:2019-03-19 15:09:08
【问题描述】:
我有很多图像存储在 S3 存储桶的单个文件夹中。共有三个类别(假设 A、B 和 C),并且图像只会属于这三个类别中的一个。我在 view-all.html 页面上呈现所有图像类别。我想要做的是在 view-all.html 中每个类别的名称旁边添加一个单独的下载按钮。单击特定下载按钮后,应将仅在该类别下的图像下载为 zip 文件。目前,下载按钮不适用于任何类别。
我只编辑了 view-all.html 和 views.py 文件。我对此进行了很多搜索,但没有找到任何确切的解决方案。我不确定是否必须在任何其他文件中添加任何其他内容。请帮帮我。提前致谢。
view-all.html
{% extends "cms/base.html" %}
{% block title %}
View-all
{% endblock %}
{% block main %}
<style>
*{box-sizing: border-box;}
.wrapper{
overflow-x:scroll;
white-space: nowrap;
}
.container {
background: #ccc;
position: relative;
height: 50%;
display: inline-block;
}
img {
padding: 0;
display: block;
margin: 0 auto auto 0;
margin-left: auto;
margin-right: auto;
max-width: 100%;
}
.overlay {
position: absolute;
bottom: 0;
background: rgb(0, 0, 0);
background: rgba(0, 0, 0, 0.5);
color: #f1f1f1;
width: 93%;
transition: .5s ease;
opacity:0;
color: white;
font-size: 20px;
padding: 20px;
text-align: center;
}
.container:hover > .overlay {
opacity: 1;
}
@media only screen and (max-width : 767px)
{
height: auto;
max-height: none;
}
</style>
{% for category in categories %}
<br /><h3>{{ category.name }}  <button name='downloadbtn' class="btn btn-primary" onclick='bulkdownload()'><i class="fa fa-download"></i> Download</button> </h3>
<div class="wrapper">
<div id="slider4" class="text-center">
{% for image in images %}
{% ifequal image.category category %}
<div class="container">
<img src="S3-url">
<br />
</div>
{% endifequal %}
{% endfor %}
</div>
</div>
{% endfor %}
{% endblock %}
views.py
@login_required
def bulkdownload(request):
if(request.GET.get('downloadbtn')):
images = Images.objects.all().filter(category = request.category.name)
if images:
categories = request.category.name
zip_subdir = '{:%B %d, %Y}'.format(datetime.now()) # name of the zip file to be downlaoded
zip_filename = '%s.zip' % zip_subdir
# Open StringIO to grab in-memory ZIP contents
s = io.StringIO.StringIO()
# The zip compressor
zf = zipfile.ZipFile(s, 'w')
for fpath in images:
# 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(), content_type = 'application/x-zip-compressed')
# ..and correct content-disposition
resp['Content-Disposition'] = 'attachment; filename=%s' % zip_filename
return resp
【问题讨论】:
-
你在哪里设置这个request.category,请提供你的javascript,它具有批量下载功能。
-
我没有使用 javascript。我不确定设置 request.category。 bulkdownload() 仅存在于 views.py 中。
标签: django python-2.7 django-models django-views zipfile