介绍 1 StreamingHttpResponse下载
2 FileResponse下载
这篇文章将为大家详细讲解有关如何在Django中使用StreamingHttpResponse与FileResponse对文件进行下载,文章内容质量较高,因此小编分享给大家做个参考,希望大家阅读完这篇文章后对相关知识有一定的了解。
1 StreamingHttpResponse下载
StreamingHttpResponse (streaming_content):流式相应,内容的迭代器形式,以内容流的方式响应。
注:StreamingHttpResponse一般多现实在页面上,不提供下载。
以下为示例代码
def streamDownload (resquest): ,def file_iterator (filepath, chunk_size =, 512): ,with 开放(filepath, & # 39; rb # 39;), as f: while 才能正确的: 时间=con 才能;f.read (512) if 才能;反对: ,,油品收率,反对 其他的才能: ,才能休息=,,filename  os.path.abspath (__file__), +, & # 39;用法# 39;=,,response  StreamingHttpResponse (file_iterator(文件名) ,return response #,最后程序会将结果打印在显示器上
2 FileResponse下载
FileResponse(流):以流形式打开后的文件
注:FileResponse是StreamingHttpResponse的子类
以下为示例代码:
def homeproc2(请求):=,,cwd  os.path.dirname (os.path.dirname (os.path.abspath (__file__)))=,,response  FileResponse(打开(时间+ cwd “msgapp/模板/youfile",,“rb")) ,响应[& # 39;- type],=, & # 39;应用程序/八进制# 39; ,响应[& # 39;附加# 39;],=,& # 39;附件;文件名=癴ilename" & # 39; ,return 响应
需要解释说明的是:
,响应[& # 39;- type],=, & # 39;应用程序/八进制# 39; ,响应[& # 39;附加# 39;],=,& # 39;附件;文件名=癴ilename" & # 39;
- <李>
- type:用于指定文件类型。
李> <李>附加项:用于指定下载文件的默认名称,对,没错!“有限公司”两个字符都要大写。
李>