django,flask,tornado下载文件

一、django

with open(file_path + file_name, "rb") as f:
    file_cont = f.read()
response = HttpResponse(file_cont)
response['Content-Type'] = 'application/octet-stream'
# python2遇到,filename为unicode中文时,无法下载,名称filename.decode("unicode_escape")
# 或者遇到中文时,from urllib.parse import quote  将中文进行URL 编码,quote(file_name)
# 或者,import codecs ex_time = codecs.encode(ex_time, 'utf-8').decode('utf-8')
response['Content-Disposition'] = 'attachment;filename="id_rsa.txt"'
return response

django的一种写法,还有好几种,不一一列出

application/octet-stream:内容类型

attachment:是否弹出确认框,加上直接下载

filename="id_rsa.txt" :下载出的文件名称

二、flask

flask的写法,还有好几种,不一一列出

response = make_response(send_from_directory(file_path, file_name, as_attachment=True))
response.headers["Content-Disposition"] = 
"attachment;filename={}".format(file_path.encode().decode('latin-1'))
return send_from_directory(file_path, file_name, as_attachment=True)


response = Response(file_cont)
response.headers['Content-Type'] = 'application/octet-stream'
response.headers['Content-Disposition'] = 'attachment;filename="id_rsa.txt"'
return response

flask访问报错:无法访问,请检查你的访问链接,看下filename是不是因为中文

解决办法:将filename编码,quote(filename),python3中只需要将python2 中 from urllib import quote 改为 from urllib.parse import quote

三、tornado

        _filename = parse.quote(filename)  # 对非ASCII进行编码防止中文乱码
        self.set_header('Content-Type', 'application/octet-stream')
        self.set_header('Content-Disposition', 'attachment;filename={}'.format(_filename))
        with open(filename, 'rb') as f:
            self.write(f.read())
        self.finish()

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值