1 streaminghttpresponse下载

streaminghttpresponse(streaming_content):流式相应,内容的迭代器形式,以内容流的方式响应。

注:streaminghttpresponse一般多现实在页面上,不提供下载。

以下为示例代码

def streamdownload(resquest):
 def file_iterator(filepath, chunk_size = 512):
 with open(filepath, 'rb') as f:
  while true:
  con = f.read(512)
  if con:
   yield con
  else:
   break
 filename = os.path.abspath(__file__) + 'test.txt'
 response = streaminghttpresponse(file_iterator(filename)
 return response 
# 最后程序会将结果打印在显示器上

2 fileresponse下载

fileresponse(stream):以流形式打开后的文件

注:fileresponse是streaminghttpresponse的子类

以下为示例代码:

def homeproc2(request):
 cwd = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
 response = fileresponse(open(cwd + "/msgapp/templates/youfile", "rb"))
 response['content-type] = 'application/octet-stream'
 response['content-disposition'] = 'attachment;filename="filename"'
 return response

需要解释说明的是:

 response['content-type] = 'application/octet-stream'
 response['content-disposition'] = 'attachment;filename="filename"'
  • content-type:用于指定文件类型。
  • content-disposition:用于指定下载文件的默认名称,对,没错! “co”两个字符都要大写。

两者都是mime协议里面的标准类型。

到此这篇关于详解django关于streaminghttpresponse与fileresponse文件下载的最优方法的文章就介绍到这了,更多相关django streaminghttpresponse与fileresponse内容请搜索www.887551.com以前的文章或继续浏览下面的相关文章希望大家以后多多支持www.887551.com!