使用 Django 生成要下载的文件
- 2025-04-17 09:02:00
- admin 原创
- 15
问题描述:
是否可以制作一个 zip 存档并提供下载,但仍不将文件保存到硬盘上?
解决方案 1:
要触发下载,您需要设置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()
解决方案 2:
创建一个临时文件会更方便。这可以节省很多内存。当你同时有多个用户时,你会发现节省内存非常非常重要。
但是,您可以写入StringIO对象。
>>> import zipfile
>>> import StringIO
>>> buffer= StringIO.StringIO()
>>> z= zipfile.ZipFile( buffer, "w" )
>>> z.write( "idletest" )
>>> z.close()
>>> len(buffer.getvalue())
778
“缓冲区”对象类似于文件,具有 778 字节的 ZIP 存档。
解决方案 3:
为什么不直接用 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
解决方案 4:
是的,您可以使用zipfile 模块、zlib 模块或其他压缩模块在内存中创建 zip 存档。您可以让视图将 zip 存档写入HttpResponse
Django 视图返回的对象,而不是将上下文发送到模板。最后,您需要将 mimetype 设置为适当的格式,以告知浏览器将响应视为文件。
解决方案 5:
模型.py
from django.db import models
class PageHeader(models.Model):
image = models.ImageField(upload_to='uploads')
视图.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)
解决方案 6:
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:
与内存中的 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
相关推荐
热门文章
项目管理软件有哪些?
热门标签
曾咪二维码
扫码咨询,免费领取项目管理大礼包!
云禅道AD