脚本之家,脚本语言编程技术及教程分享平台!
分类导航

Python|VBS|Ruby|Lua|perl|VBA|Golang|PowerShell|Erlang|autoit|Dos|bat|

服务器之家 - 脚本之家 - Python - Python+django实现文件下载

Python+django实现文件下载

2020-08-06 11:39脚本之家 Python

本文是python+django系列的第二篇文章,主要是讲述是先文件下载的方法和代码,有需要的小伙伴可以参考下。

(1)方法一、直接用a标签的href+数据库中文件地址,即可下载。缺点:word excel是直接弹框下载,对于image txt 等文件的下载方式是直接在新页面打开。

(2)方法二、在python后台对下载内容进项处理,返回内容直接弹出下载框。

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#后台处理函数
def downloadFile(req):
  filename=basePath+req.GET['url']
  def file_iterator(file_name, chunk_size=512):
    with open(file_name) as f:
      while True:
        c = f.read(chunk_size)
        if c:
          yield c
        else:
          break
  response = StreamingHttpResponse(file_iterator(filename))
  response['Content-Type'] = 'application/octet-stream'
  response['Content-Disposition'] = 'attachment;filename="{0}"'.format(filename)
  return response

(3)前台使用函数方法

①、a标签调用函数传入路径<a href='/downloadFile/url=路径'>

②、button标签调用jq方法调用后台函数

?
1
<input type='button' class='download'>
?
1
2
3
#下载按钮点击事件
$("body").on("click",".download",function(){3   location.href="/downloadFile/?url="+路径;
});

延伸 · 阅读

精彩推荐