我有一个复选框表单。我正在尝试这样做,如果用户选中“视频”框并提交表单,那么视频文件会被压缩,django 会生成一个动态下载,该下载会弹出在用户屏幕上。我希望音频也能发生同样的情况。但是,如果用户同时选中复选框并提交,则音频和视频文件将合并在一个 zip 中,并为用户弹出下载。我不希望任何这些存储在磁盘上,所以我使用 StringIO。没有下载弹出窗口出现
html
<form>
<input type="checkbox" name="list" value="audio"/> Audio<br />
<input type="checkbox" name="list" value="video"/> Video<br />
<input type="submit" value="submit" />
</form>
Python
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
import cgitb; cgitb.enable()
import cgi
from zipfile import ZipFile
from StringIO import StringIO
from django.http import HttpResponse
from django.core.servers.basehttp import FileWrapper
files = 0
def zip (content):
buffer= StringIO.StringIO()
z= zipfile.ZipFile( buffer, "w" )
z.writestr(content)
z.close()
# generate the file
response = HttpResponse(FileWrapper(z), content_type='application/zip')
response['Content-Disposition'] = 'attachment; filename=z.zip'
return response
form = cgi.FieldStorage()
mylist = form.getlist('list')
print 'Content-Type: text/plain\n'
for item in mylist:
if item == 'video':
files = '../download/video.html'
zip(files)
elif item == 'audio':
files = '../download/audio.html'
zip(files)
elif item == 'audio' and 'video':
files = '../download/audio.html'+'../download/video.html'
zip(files)
else:
print 'nothing selected'