简单了解django文件下载方式

发布时间:2020-09-20 02:17:18 作者:xushukui
来源:脚本之家 阅读:197

这篇文章主要介绍了简单了解django三种文件下载方式,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下

推荐使用FileResponse,从源码中可以看出FileResponse是StreamingHttpResponse的子类,内部使用迭代器进行数据流传输。

在实际的项目中很多时候需要用到下载功能,如导excel、pdf或者文件下载,当然你可以使用web服务自己搭建可以用于下载的资源服务器

如nginx,这里我们主要介绍django中的文件下载。

实现方式:a标签+响应头信息(当然你可以选择form实现)

<div class="col-md-4"><a href="{% url 'download' %}" rel="external nofollow" >点我下载</a></div>

方式一:使用HttpResponse
路由url:
    url(r'^download/',views.download,name="download"),
views.py代码
    from django.shortcuts import HttpResponse
    def download(request):
       file = open('crm/models.py', 'rb')
       response = HttpResponse(file)
       response['Content-Type'] = 'application/octet-stream' #设置头信息,告诉浏览器这是个文件
       response['Content-Disposition'] = 'attachment;filename="models.py"'
       return response
    方式二:使用StreamingHttpResponse, 其他逻辑不变,主要变化在后端处理:
      from django.http import StreamingHttpResponse
      def download(request):
         file=open('crm/models.py','rb')
         response =StreamingHttpResponse(file)
         response['Content-Type']='application/octet-stream'
         response['Content-Disposition']='attachment;filename="models.py"'
         return response
方式三:使用FileResponse
from django.http import FileResponse
def download(request):
 file=open('crm/models.py','rb')
 response =FileResponse(file)
 response['Content-Type']='application/octet-stream'
 response['Content-Disposition']='attachment;filename="models.py"'
 return response

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持亿速云。

推荐阅读:
  1. 简单了解tengine
  2. 简单了解SSL/TLS协议

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

django 文件 下载

上一篇:解决vue同一slot在组件中渲染多次的问题

下一篇:spring boot整合hessian的示例

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》