yre*_*uta 21 python django file
可能重复:
在Django中提供动态生成的ZIP存档
(如果我错过了任何可能的副本,请随时指出我)
我看过这个片段:http: //djangosnippets.org/snippets/365/
这个答案:
但我想知道如何调整它们以满足我的需要:我希望压缩多个文件,并通过链接下载(或通过视图动态生成)存档.我是Python和Django的新手,所以我不知道如何去做.
预先感谢!
dbr*_*dbr 57
我已将此发布在Willy链接的重复问题上,但由于赏金问题不能作为副本关闭,因此也可以将其复制到此处:
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 = ["/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
因此,据我所知,您的问题不是如何动态生成此文件,而是创建一个供人们下载它的链接...
我的建议如下:
0) 为您的文件创建一个模型,如果您想动态生成它,请不要使用 FileField,而只使用生成此文件所需的信息:
class ZipStored(models.Model):
    zip = FileField(upload_to="/choose/a/path/")
1) 创建并存储您的 Zip。这一步很重要,您在内存中创建 zip,然后将其转换为将其分配给 FileField:
function create_my_zip(request, [...]):
    [...]
    # This is a in-memory file
    file_like = StringIO.StringIO()
    # Create your zip, do all your stuff
    zf = zipfile.ZipFile(file_like, mode='w')
    [...]
    # Your zip is saved in this "file"
    zf.close()
    file_like.seek(0)
    # To store it we can use a InMemoryUploadedFile
    inMemory = InMemoryUploadedFile(file_like, None, "my_zip_%s" % filename, 'application/zip', file_like.len, None)
    zip = ZipStored(zip=inMemory)
    # Your zip will be stored!
    zip.save()
    # Notify the user the zip was created or whatever
    [...]
2)创建一个url,例如获取一个与id匹配的数字,你也可以使用一个slugfield(this)
url(r'^get_my_zip/(\d+)$', "zippyApp.views.get_zip")
3) 现在是视图,该视图将返回与 url 中传递的 id 匹配的文件,您也可以使用发送文本而不是 id 的 slug,并通过您的 slugfield 进行 get 过滤。
function get_zip(request, id):
    myzip = ZipStored.object.get(pk = id)
    filename = myzip.zip.name.split('/')[-1]
    # You got the zip! Now, return it!
    response = HttpResponse(myzip.file, content_type='application/zip')
    response['Content-Disposition'] = 'attachment; filename=%s' % filename
| 归档时间: | 
 | 
| 查看次数: | 28630 次 | 
| 最近记录: |