在Flask中读取MySQL数据库中的图片并返回给前端,主要有两种实现方式:
CREATE TABLE images (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(100),
data LONGBLOB,
mimetype VARCHAR(50)
);
from flask import Flask, send_file, Response
from io import BytesIO
import pymysql
app = Flask(__name__)
# 数据库配置
db_config = {
'host': 'localhost',
'user': 'your_username',
'password': 'your_password',
'database': 'your_database'
}
@app.route('/image/<int:image_id>')
def get_image(image_id):
try:
# 连接数据库
conn = pymysql.connect(**db_config)
cursor = conn.cursor()
# 查询图片数据
cursor.execute("SELECT data, mimetype FROM images WHERE id = %s", (image_id,))
img_data, mimetype = cursor.fetchone()
# 关闭连接
cursor.close()
conn.close()
if img_data:
# 返回图片响应
return Response(img_data, mimetype=mimetype)
else:
return "Image not found", 404
except Exception as e:
return str(e), 500
if __name__ == '__main__':
app.run(debug=True)
<img src="/image/1" alt="Database Image">
更常见的做法是将图片存储在文件系统中,数据库中只保存图片路径。
CREATE TABLE images (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(100),
path VARCHAR(255)
);
from flask import Flask, send_from_directory
import os
import pymysql
app = Flask(__name__)
# 数据库配置
db_config = {
'host': 'localhost',
'user': 'your_username',
'password': 'your_password',
'database': 'your_database'
}
# 图片存储目录
IMAGE_FOLDER = 'static/images'
@app.route('/image/<int:image_id>')
def get_image(image_id):
try:
# 连接数据库
conn = pymysql.connect(**db_config)
cursor = conn.cursor()
# 查询图片路径
cursor.execute("SELECT path FROM images WHERE id = %s", (image_id,))
path = cursor.fetchone()[0]
# 关闭连接
cursor.close()
conn.close()
if path:
# 返回图片文件
return send_from_directory(IMAGE_FOLDER, path)
else:
return "Image not found", 404
except Exception as e:
return str(e), 500
if __name__ == '__main__':
app.run(debug=True)
<img src="/image/1" alt="Database Image">
from flask import Flask, request, jsonify
import pymysql
app = Flask(__name__)
# 数据库配置
db_config = {
'host': 'localhost',
'user': 'your_username',
'password': 'your_password',
'database': 'your_database'
}
@app.route('/upload', methods=['POST'])
def upload_image():
if 'file' not in request.files:
return jsonify({'error': 'No file part'}), 400
file = request.files['file']
if file.filename == '':
return jsonify({'error': 'No selected file'}), 400
try:
# 读取文件数据
img_data = file.read()
mimetype = file.mimetype
# 连接数据库
conn = pymysql.connect(**db_config)
cursor = conn.cursor()
# 插入图片数据
cursor.execute(
"INSERT INTO images (name, data, mimetype) VALUES (%s, %s, %s)",
(file.filename, img_data, mimetype)
)
conn.commit()
# 获取插入的ID
image_id = cursor.lastrowid
# 关闭连接
cursor.close()
conn.close()
return jsonify({'success': True, 'image_id': image_id}), 200
except Exception as e:
return jsonify({'error': str(e)}), 500
if __name__ == '__main__':
app.run(debug=True)
以上两种方法都能实现从MySQL读取图片并返回给前端,根据实际需求选择合适的方式。