1

我有一个复选框表单。我正在尝试这样做,如果用户选中“视频”框并提交表单,那么视频文件会被压缩,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'
4

1 回答 1

1

为了确保 for 循环不能工作,最后一个 elif 中的第三个代码将永远不会执行,因为它与第二个相同,与第二 个item == 'audio' and 'video' 相同item == 'audio and True'item == 'audio'

我会更改循环代码以使其看起来更简单

files = []
for item in mylist:
  if item == 'video':
    files.append('../download/video.html')
  elif item == 'audio':
    files.append('../download/audio.html')
zip(files)

然后重构 zip 以处理文件列表

def zip (filenames):
    buffer= StringIO.StringIO()
    z= zipfile.ZipFile( buffer, "w" )
    [z.writestr(f) for f in filenames]
    z.close()
    # generate the file
    response = HttpResponse(FileWrapper(z), content_type='application/zip')
    response['Content-Disposition'] = 'attachment; filename=z.zip'
    return response

You also have to make sure that the view functions returns what the zip function returns.

于 2012-06-12T07:36:40.397 回答