文件下载

Django的Httpresponse对象允许将迭代器作为传入参数。StreamingHttpResponse对象取代HttpRseponse对象,更适合与文件下载。服务器上的文件已经通过文件流传输到浏览器上,单文件流会一乱码的方式显示在浏览器中,而不是下载在硬盘中,可以给StreamHttpResponse对象的Content_type 和 Content_Disposition字段赋值 Content_type :http://tool.oschina.net/commons(指明文件的格式)
当文件为多个文件是自动生成zip格式的压缩包

from django.http import StreamingHttpResponse
def big_file_download(request):
   def file_iterator(file_name, chunk_size=512):    
      with open('static/app/app.apk') as f:       
           while True:            
                c = f.read(chunk_size)            
                if c:                
                      yield c            
                else:                
                      break
  the_file_name = "big_file.apk"
  response = StreamingHttpResponse(file_iterator(the_file_name))
  response['Content-Type'] = 'application/application/vnd.android.package-archive'
  response['Content-Disposition'] = 'attachment;filename="  {0}"'.format(the_file_name)
  return response
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容