Flask+MySQL:如何从数据库读取图片并在HTML页面展示?
从MySQL数据库检索图片并在HTML网站显示的正确实现
现有代码的核心问题
- SQL参数传递错误:单个参数需加逗号写成
(ViewCustomerId,),否则会被解析为字符串序列 - 图片数据处理冗余:无需用
Image.open,直接对数据库返回的二进制数据做base64编码即可 - 模板变量不匹配:后端传递的变量是
image,前端模板调用的是image_data,名称不一致 - 字典取值错误:使用
DictCursor时,fetchone()返回字典,需通过键名image获取二进制数据
修正后的app.py代码
@app.route('/customerDetails', methods=['GET', 'POST']) def customerDetails(): message = '' if "logged in" in session and session['role'] == 'admin': user = session["username"] ViewCustomerId = request.args.get('customerid') cur = mysql.connection.cursor(MySQLdb.cursors.DictCursor) # 查询用户基础信息 cur.execute('SELECT * FROM user WHERE id = %s', (ViewCustomerId,)) Viewcustomer = cur.fetchone() customer = None image_data = None if Viewcustomer: customer = Viewcustomer # 查询图片二进制数据 cur.execute('SELECT image FROM user WHERE id = %s', (ViewCustomerId,)) image_row = cur.fetchone() if image_row and image_row['image']: # 将二进制数据转为base64字符串,供前端渲染 image_data = base64.b64encode(image_row['image']).decode('utf-8') else: message = '该客户不存在于数据库中' cur.close() # 释放数据库游标资源 return render_template("customerDetails.html", user=user, customer=customer, image_data=image_data, message=message) else: return redirect(url_for("home"))
修正后的customerDetails.html代码
{% if image_data %} <img class="" src="data:image/jpeg;base64,{{ image_data }}" alt="客户头像" width="350" height="350" /> {% else %} <p>暂无图片</p> {% endif %}
关键注意事项
- 数据库字段要求:确保
user表的image字段类型为BLOB(或MEDIUMBLOB/LONGBLOB,根据图片大小选择),用于存储二进制图片数据 - 编码转换:
base64.b64encode()返回字节串,必须用.decode('utf-8')转为字符串才能在模板中正常渲染 - 空值处理:增加图片不存在时的提示逻辑,避免前端显示无效图片标签
- 资源释放:操作完成后关闭数据库游标,防止资源泄漏
内容的提问来源于stack exchange,提问作者Sefiu Rasheed
相关产品推荐
相关产品推荐

