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':文件路径}), 
  • 相关阅读:
    cmd 命令添加防火墙端口
    linux 远程 telnet
    topshelf 服务启动运行
    postfix 邮箱服务器- SPF 防发件人欺骗
    linux 只查看目录下文件夹
    Android中的颜色设置
    thread和runnable
    Handler总结
    Failed to install Intel HAXM.
    Android Studio常见问题总结
  • 原文地址:https://www.cnblogs.com/liuq/p/4792557.html
Copyright © 2011-2022 走看看