加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

django 中实现文件下载的3种方式

发布时间:2020-12-20 10:31:02 所属栏目:Python 来源:网络整理
导读:方法一:使用HttpResponse from django.shortcuts import HttpResponse def file_down(request): file =open( ‘ /home/amarsoft/download/example.tar.gz ‘ , ‘ rb ‘ ) response = HttpResponse(file) response[ ‘ Content-Type ‘ ]= ‘ application/o

方法一:使用HttpResponse
from django.shortcuts import HttpResponse def file_down(request): file=open(/home/amarsoft/download/example.tar.gz,rb) response =HttpResponse(file) response[Content-Type]=application/octet-stream response[Content-Disposition]=attachment;filename="example.tar.gz" return response 方法二:使用StreamingHttpResponse from django.http import StreamingHttpResponse def file_down(request): file=open(/home/amarsoft/download/example.tar.gz,rb) response =StreamingHttpResponse(file) response[Content-Type]=application/octet-stream response[Content-Disposition]=attachment;filename="example.tar.gz" return response 方法三:使用FileResponse from django.http import FileResponse def file_down(request): file=open(/home/amarsoft/download/example.tar.gz,rb) response =FileResponse(file) response[Content-Type]=application/octet-stream response[Content-Disposition]=attachment;filename="example.tar.gz" return response

总结:对比 虽然使用这三种方式都能实现,但是推荐用FileResponse, 在FileResponse中使用了缓存,更加节省资源。 虽说是三种方式,但是原理相同,说白了就是一种方式。

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读