import os
import pathlib
import mimetypes
from flask import Flask,Response,make_response,send_from_directory
base_path = pathlib.Path(__file__).parent
app = Flask(__name__)
'''
下载的时候要注意的问题:
1.设置响应请求头的类型 : Content-Type 平常都是json格式,文件的话是其他的格式
2.告诉浏览器当前下载的作为浏览器的附件下载属性: Content-Disposition https://cloud.tencent.com/developer/section/1189916
'''
@app.route('/dow')
def dow():
path = os.path.join(base_path,'下载文件.txt')
file = open(path,mode='rb')
# response = make_response(file)
# response.default_mimetype = 'text/html'
# response['Content-Disposition']='attachment; filename="filename.txt"'
'''
path: 下载的文的路径 相当于 open(path,mode='rb') Content-Type: text/plain; charset=utf-8
filename:下载文件的名称和后缀 相当于请求头中的 filename="filename.txt
directory: 当前下载文件的父级路径
as_attachment : False则浏览器返回文件预览 如果该文件可以被浏览器渲染 response['Content-Disposition']='attachment;
'''
return send_from_directory(path=path,filename='下载文件.txt',as_attachment=False,directory=base_path)
@app.route('/dow2')
def uploaded_file():
path = os.path.join(base_path,'下载文件.txt')
f = open(path, "rb")
res = Response(f.readlines())
mime_type = mimetypes.guess_type(path)[0]
res.headers['Content-Type'] = mime_type
res.headers['Content-Disposition'] = "attachment; filename=filename.txt"
return res
if __name__ == '__main__':
app.run()
资料案例
https://blog.csdn.net/li627528647/article/details/77544136
https://blog.csdn.net/qq_44198436/article/details/106922355
https://blog.csdn.net/WJ844908240/article/details/102517072
标签:__,功能,Flask,filename,Content,path,txt,下载
From: https://www.cnblogs.com/wkxz/p/17157680.html