我已经在Willy链接到的重复问题上发布了此问题,但是由于无法将包含悬赏的问题作为重复问题解决,因此也可以在此处将其复制:
import osimport zipfileimport StringIOfrom django.http import HttpResponsedef getfiles(request): # Files (local path) to put in the .zip # FIXME: Change this (get paths from DB etc) filenames = ["/tmp/file1.txt", "/tmp/file2.txt"] # 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



