接下来看下如何生成文件,在网站上经常要下载后台的文件或者是显示后台文件的内容。
下面通过HttpResponse的方法可以直接将读取的内容显示在网页上
def test1(request): with open(r'd:/django_test2/django.txt') as f: c=f.read() return HttpResponse(c)但是这种方法只适合小文件,如果遇到大的文件则会很耗内存。
Django中提供了StreamingHttpResponse可以以流的方式进行下载。代码如下。
from django.http import StreamingHttpResponse def test1(request): def file_itertor(file_name,chunk_size=512): with open(file_name) as f: while True: c=f.read(chunk_size) if c: yield c else: break file_name=r'd:/django_test2/django.txt' download_file='django.txt' response=StreamingHttpResponse(file_itertor(file_name)) response['Content-Type'] = 'application/octet-stream' response['Content-Disposition'] = 'attachment;filename="{0}"'.format(download_file) return response如果没有设置Content-Type和Content-Disposition,那么文件流会直接显示在浏览器上,如果要下载到硬盘上则必须设置Content-Type和Content-Disposition。其中download_file为下载的时候显示的文件名。
刷新网页的时候,会自动下载该文件
最后来看下PDF文档的生成。
首先要安装一个reportlab。pip install reportlab
生成代码如下:
def test1(request): response = HttpResponse(content_type='application/pdf') response['Content-Disposition'] = 'attachment; filename="django-pdf.pdf"' p = canvas.Canvas(response) p.drawString(50, 50, "Hello django.") p.showPage() p.save() return response刷新在浏览器中自动下载生成的PDF文件
生成的pdf文件内容。
转载于:https://www.cnblogs.com/zhanghongfeng/p/8254112.html
相关资源:JAVA上百实例源码以及开源项目