flask实现⽂件预览或下载
实现⽂件下载的关键,是在response的headers中加⼊Content-Disposition, ⽽对于⽂件预览与下载,需要的参数值不同:⽂件下载:
{
"Content-Disposition":"attachement;filename=7415f814ddd111eaa0b0f8597131cd0b.pdf",
"Content-Type":"application/pdf"
}
⽂件预览:
{
"Content-Disposition":"inline;filename=7415f814ddd111eaa0b0f8597131cd0b.pdf",
"Content-Type":"application/pdf"
}
from flask import jsonify, request, send_file, make_response
from flask_restful import Resource
from comm.decorators import login_reqire
ptions import BadRequest
from comm import errors
port_dataservice import ReportDataservice
from web.port_argparse import download_report_parser
sponse import ResponsesObj
from comm.log import logger
class DownloadReport(Resource):
@login_reqire
flask下载
def post(self):
try:
args = download_report_parser.parse_args()
sid = ("sid")
report_id = ("report_id")
download = ("download")or False
user = request.user
file_path = _report_path(sid, user.uid, report_id)
except BadRequest:
return jsonify(ResponsesObj.InvalidArgsResponse)
except errors.NotExistsException:
return jsonify(ResponsesObj.NotExistsResponse)
except Exception as e:
<(e)
return jsonify(ResponsesObj.SystemExceptionResponse)
if not download:
headers =("Content-Disposition", f"inline;filename={report_id}.pdf")
as_attachment =False
else:
headers =(f"Content-Disposition", f"attachement;filename={report_id}.pdf")
as_attachment =True
response = make_response(send_file(filename_or_fp= file_path, as_attachment=as_attachment))
response.headers[headers[0]]= headers[1]
return response
header的本质是dict,字典或者map
通过前端传⼊的download参数判断要返回的header,这个是我返回的header
{
"Content-Length":"240463",
"Content-Type":"application/pdf",
"Last-Modified":"Fri, 14 Aug 2020 01:59:33 GMT",
"Cache-Control":"public, max-age=43200",
"Expires":"Fri, 14 Aug 2020 23:14:15 GMT", "ETag":"\"1597370373.8080895-240463-2387490041\"",
"Content-Disposition":"inline;filename=7415f814ddd111eaa0b0f8597131cd0b.pdf" }
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论