一、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()