如何在Django中使用StreamingHttpResponse与FileResponse对文件进行下载

这篇文章将为大家详细讲解有关如何在Django中使用StreamingHttpResponse与FileResponse对文件进行下载,文章内容质量较高,因此小编分享给大家做个参考,希望大家阅读完这篇文章后对相关知识有一定的了解。

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”两个字符都要大写。

关于如何在Django中使用StreamingHttpResponse与FileResponse对文件进行下载就分享到这里了,希望以上内容可以对大家有一定的帮助,可以学到更多知识。如果觉得文章不错,可以把它分享出去让更多的人看到。