zoukankan      html  css  js  c++  java
  • django 从零开始 13 返回文件

    进行一些操作返回文件,flask和django差不多,基本都是在返回response 并且对其中的返回头部写入返回文件信息

    # image
    def image(request):
        f = open(r'C:UsersAdministratorDesktop反面.jpg','rb').read()
        return HttpResponse(f,content_type='image/jpg')
    
    
    # csv
    import csv
    UNRULY_PASSENGERS = [146,184,235,200,226,251,299,273,281,304,203]
    def to_csv(request):
        response = HttpResponse(content_type='text/csv')
        response['Content-Disposition'] = 'attachment; filename=ceshi.csv' # 下载csv文件名设置filename b不能中文
    
        writer = csv.writer(response)
        writer.writerow(['Year', 'Unruly Airline Passengers'])
        for (year, num) in zip(range(1995, 2006), UNRULY_PASSENGERS):
            writer.writerow([year, num])
    
        return response
    
    # pdf
    from reportlab.pdfgen import canvas
    def to_pdf(request):
        response = HttpResponse(content_type='application/pdf')
        response['Content-Disposition'] = 'attachment; filename=ceshi_pdf.pdf'
    
        p = canvas.Canvas(response)
    
        p.drawString(500, 200, "Hello world.")   # 和csv一样,坐标位置是从左下角开始的
    
        p.showPage()
        p.save()
        return response
    
    
    
    # 对大型文件进行一个内存操作,如果内容不大,可以使用上面的办法
    from io import BytesIO
    from reportlab.pdfgen import canvas
    from django.http import HttpResponse
    def to_max_pdf(request):
        response = HttpResponse(content_type='application/pdf')
        response['Content-Disposition'] = 'attachment; filename=ceshi_max.pdf'
    
        temp = BytesIO()           #BytesIO是编码内容保存在内存中
    
        p = canvas.Canvas(temp)
    
        p.drawString(100, 100, "Hello world.")
    
        p.showPage()
        p.save()                    
    
        response.write(temp.getvalue())
        return response
  • 相关阅读:
    .NET 4 上的REST 框架
    WCF Web API 说再见,继承者ASP.NET Web API
    基于盛大的云数据库系统 MongoIC 构建图片系统
    微软以Apache许可协议开源ASP.NET MVC
    Redis 起步
    HttpClient介绍
    Quartz.NET 2.0正式发布
    CodeFirst Migrations随Entity Framework 4.3一同发布
    Redis 在Centos Linux 上的启动脚本
    Quartz.NET的管理工具
  • 原文地址:https://www.cnblogs.com/zengxm/p/11332936.html
Copyright © 2011-2022 走看看