zoukankan      html  css  js  c++  java
  • Django 之 下载文件

    法I:

    views.py

     1 #encoding:utf-8
     2 import os
     3 
     4 from django.core.servers.basehttp import FileWrapper
     5 from django.http import HttpResponse
     6 
     7 path = '/tmp/'
     8 def downloader(request):
     9     filename_tmp = 'test.tmp'   # test.tmp为将要被下载的文件名
    10     filename = os.path.join(path,filename_tmp)
    11     wrapper = FileWrapper(file(filename))
    12     response = HttpResponse(wrapper, content_type='text/plain')
    13     response['Content-Length'] = os.path.getsize(filename)
    14     response['Content-Disposition'] = 'attachment; filename="somefilename.csv"'    # somefilename.csv为下载后的文件名
    15     return response

    法II:

    test.html

    <a href="download/file/">下载</a>

     urls.py

    1 url(r'^download/file/$', 'xxx.views.download'),    # xxx为项目名

    xxx中的views.py

     1 import os
     2 from django.http import HttpResponse
     3 from django.contrib.auth.decorators import login_required
     4 
     5 @login_required
     6 def download(request):
     7     response = HttpResponse()
     8     response['Content-Disposition'] = 'attachment;filename=downfile.txt'    # downfile.txt为下载后的文件名
     9     full_path = os.path.join('/tmp', 'filename.txt')    # filename.txt为将要被下载的文件名
    10     if os.path.exists(full_path):
    11         response['Content-Length'] = os.path.getsize(full_path)    #  可不加
    12         content = open(full_path, 'rb').read()
    13         response.write(content)
    14         return response
    15     else:
    16         return HttpResponse(u'文件未找到')

    法III:

    test.html

    <a href="download/downfile.txt">下载</a>

    urls.py

     1 url(r'^download/(?P.*)$', 'django.views.static.serve',{'document_root':文件路径}), 
  • 相关阅读:
    SLS评测报告
    Flash对不同的浏览器的兼容性
    NodeJS的Cluster模块使用
    Varnish+Xcache构建高性能WEB构架初探
    Memcached Client的释疑
    Firebug及YSlow简介与使用图文详解
    PHP Memcached 实现简单数据库缓存
    PHP + Memcache 实现Session共享
    Linux 开机关机在线求助与指令输入
    Linux 基础学习篇笔记 Linux基础知识
  • 原文地址:https://www.cnblogs.com/liuq/p/4792557.html
Copyright © 2011-2022 走看看