使用Django生成要下载的文件

时间:2009-05-25 22:26:02

标签: python django

是否可以制作zip存档并提供下载,但仍然不能将文件保存到硬盘中?

8 个答案:

答案 0 :(得分:110)

要触发下载,您需要设置Content-Disposition标题:

from django.http import HttpResponse
from wsgiref.util import FileWrapper

# generate the file
response = HttpResponse(FileWrapper(myfile.getvalue()), content_type='application/zip')
response['Content-Disposition'] = 'attachment; filename=myfile.zip'
return response

如果您不想要磁盘上的文件,则需要使用StringIO

import cStringIO as StringIO

myfile = StringIO.StringIO()
while not_finished:
    # generate chunk
    myfile.write(chunk)

您也可以选择设置Content-Length标题:

response['Content-Length'] = myfile.tell()

答案 1 :(得分:26)

创建临时文件会更快乐。这节省了大量内存。当你同时拥有一个或两个以上的用户时,你会发现节省内存是非常非常重要的。

但是,您可以写入StringIO对象。

>>> import zipfile
>>> import StringIO
>>> buffer= StringIO.StringIO()
>>> z= zipfile.ZipFile( buffer, "w" )
>>> z.write( "idletest" )
>>> z.close()
>>> len(buffer.getvalue())
778

“缓冲区”对象与文件类似,带有778字节的ZIP存档。

答案 2 :(得分:10)

为什么不制作tar文件呢?像这样:

def downloadLogs(req, dir):
    response = HttpResponse(content_type='application/x-gzip')
    response['Content-Disposition'] = 'attachment; filename=download.tar.gz'
    tarred = tarfile.open(fileobj=response, mode='w:gz')
    tarred.add(dir)
    tarred.close()

    return response

答案 3 :(得分:9)

是的,您可以使用zipfile modulezlib module或其他compression modules在内存中创建zip存档。您可以使视图将zip存档写入Django视图返回的HttpResponse对象,而不是将上下文发送到模板。最后,您需要将mimetype设置为适当的格式tell the browser to treat the response as a file

答案 4 :(得分:6)

models.py

from django.db import models

class PageHeader(models.Model):
    image = models.ImageField(upload_to='uploads')

views.py

from django.http import HttpResponse
from StringIO import StringIO
from models import *
import os, mimetypes, urllib

def random_header_image(request):
    header = PageHeader.objects.order_by('?')[0]
    image = StringIO(file(header.image.path, "rb").read())
    mimetype = mimetypes.guess_type(os.path.basename(header.image.name))[0]

    return HttpResponse(image.read(), mimetype=mimetype)

答案 5 :(得分:5)

答案 6 :(得分:5)

def download_zip(request,file_name):
    filePath = '<path>/'+file_name
    fsock = open(file_name_with_path,"rb")
    response = HttpResponse(fsock, content_type='application/zip')
    response['Content-Disposition'] = 'attachment; filename=myfile.zip'
    return response

您可以根据自己的要求替换zip和内容类型。

答案 7 :(得分:4)

与内存中的tgz存档相同:

import tarfile
from io import BytesIO


def serve_file(request):
    out = BytesIO()
    tar = tarfile.open(mode = "w:gz", fileobj = out)
    data = 'lala'.encode('utf-8')
    file = BytesIO(data)
    info = tarfile.TarInfo(name="1.txt")
    info.size = len(data)
    tar.addfile(tarinfo=info, fileobj=file)
    tar.close()

    response = HttpResponse(out.getvalue(), content_type='application/tgz')
    response['Content-Disposition'] = 'attachment; filename=myfile.tgz'
    return response
相关问题