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':文件路径}), 
  • 相关阅读:
    fiddler居然有mac版本了
    java学习笔记02 导入,方法调用,私有公有,静态非静态
    apscheduler笔记
    java学习笔记01 类型,List,Set,循环
    fiddler笔记
    为什么有些端口不能用?
    ubuntu借网
    filecoin
    django密码生成
    python-panda
  • 原文地址:https://www.cnblogs.com/liuq/p/4792557.html
Copyright © 2011-2022 走看看