读取本地图片返回给前端有如下几种方式:
1. 通过send_from_directory函数
# -*- coding: utf-8 -*-
from flask import Flask, render_template, send_file, send_from_directory,json, jsonify,make_response
@app.route('/get_file/', methods=['GET'])
def get_file(file_name):
basedir = os.path.abspath(os.path.dirname(__file__))
# basedir一般是在配置文件中
try:
response = make_response(
send_from_directory(basedir, file_name, as_attachment=True))
return response
except Exception as e:
return f"文件读取异常{e}"
2. send_file函数
# -*- coding: utf-8 -*-
from flask import Flask, render_template, send_file
@app.route('/get_file/', methods=['GET'])
def get_local_resource(file_name):
basedir = os.path.abspath(os.path.dirname(__file__))
# basedir一般是在配置文件中
file_path = os.path.join(basedir, file_name)
# 向api返回(图片)文件
return send_file(file_path)
3. 从本地读取文件流,构建respone对象
from app import app
from urllib.parse import quote
from flask import jsonify, request, make_response
from werkzeug.utils import secure_filename
@app.route('/api/down/', methods=['GET'])
def down_file(filename):
basedir = os.path.abspath(os.path.dirname(__file__))
# basedir一般是在配置文件中
if filename is None:
return "未找到该文件!"
file = open(os.path.join(basedir, '%s' % filename), "rb").read()
response = make_response(file)
utf_filename = quote(filename.encode("utf-8"))
response.headers["Content-Disposition"] = "attachment;filename*=utf-8''{}".format(utf_filename)
response.headers["Content-Type"] = "application/octet-stream; charset=UTF-8"
return response