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

    方法一、

    from django.http import StreamingHttpResponse 
    
    def big_file_download(request):   
    
     # do something...    
    
        def file_iterator(file_name, chunk_size=512):        
    
            with open(file_name) as f:            
    
                while True:                
    
                    c = f.read(chunk_size)                
    
                        if c:                    
    
                            yield c                
    
                        else:                    
    
                            break   
    
        the_file_name = "file_name.txt"   
    
        response = StreamingHttpResponse(file_iterator(the_file_name))    
    
        return response
     
    

    方法二、

     csv格式

    #urls.py
    
    url(r'download/(?P<FILE>.*)$', views.DownLoadView.as_view(), name='download'),
    
    
    
    #views.py
    
    class DownLoadView(View):
    
        def get(self, request, FILE):
    
            file_path = STATICFILES_DIRS[0] +"/"+FILE
    
            response = HttpResponse(content_type="text/csv") 
    
            response['Content-Disposition'] = 'attachment; filename=%s' %FILE
    
            response['Content-Length'] = os.path.getsize(file_path) 
    
            data = csv.reader(file(file_path, 'rb'))
    
            writer = csv.writer(response)
    
            for item in data:
    
               writer.writerow(item) 
    
            return response
    

      

    方法三、

    #urls.py
    
    url(r'loadkml/(.*)$', 'django.views.static.serve', {'document_root':settings.DOWNLOAD_DIR}, name='loadkml'),
    
    
    
    #settings.py
    
    DOWNLOAD_DIR = os.path.join(BASE_DIR, "data").replace('\', '/')
    

      

  • 相关阅读:
    第二阶段冲刺6
    第二阶段冲刺5
    第二阶段冲刺4
    第二阶段冲刺3
    暑假学习进度七
    暑假学习进度六
    暑假学习进度五
    暑假学习进度四
    暑假学习进度三
    暑假学习进度二
  • 原文地址:https://www.cnblogs.com/zhengze/p/10701231.html
Copyright © 2011-2022 走看看