You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Flask SQLAlchemy上传图片至数据库后无法在HTML中显示

Flask图片上传后无法在HTML显示的问题修复

问题描述

使用Flask SQLAlchemy实现图片上传功能,图片已成功存入数据库,但在HTML浏览器中仅显示小图片图标,无任何报错信息。

相关代码

main.py

from flask import Flask, render_template, redirect, url_for
from flask_sqlalchemy import SQLAlchemy
from flask_wtf import FlaskForm
from flask_wtf.file import FileField, FileRequired, FileAllowed
from wtforms import SubmitField
from sqlalchemy import Integer, String
from sqlalchemy.orm import Mapped, mapped_column, Base
import os
from werkzeug.utils import secure_filename

app = Flask(__name__)
app.config["UPLOAD_PATH"] = "static/"

app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///db.db'
db = SQLAlchemy(model_class=Base)
db.init_app(app)

APP_ROOT = os.path.dirname(os.path.abspath(__file__))
UPLOAD_PATH = os.path.join(APP_ROOT, 'uploads')

class Gallery(db.Model):
    __tablename__ = "gallery"
    id: Mapped[int] = mapped_column(Integer, primary_key=True)
    image: Mapped[str] = mapped_column(String(500))

class GalleryForm(FlaskForm):
    image = FileField('Add Gallery Photo', validators=[FileRequired(), FileAllowed(['jpg','png'], 'Images only!')])
    submit = SubmitField("Add Gallery Photo")

@app.route('/admin', methods=["GET", "POST"])
def index():
    gallery_form = GalleryForm()
    if gallery_form.validate_on_submit():
        new_gallery = Gallery()

        # Handling file upload
        uploaded_file = gallery_form.image.data
        filename = secure_filename(uploaded_file.filename)
        image_path = os.path.join(app.config['UPLOAD_PATH'], filename)
        uploaded_file.save(image_path)
        new_gallery.image = image_path
        path_list = new_gallery.image.split('/')[1:]
        new_path = '/'.join(path_list)

        new_gallery.image = new_path

        db.session.add(new_gallery)
        db.session.commit()
        return redirect(url_for('index'))

    gallery_image = db.session.execute(db.select(Gallery)).scalars().all()
    return render_template("index.html", all_gallery=gallery_image, gallery_form=gallery_form)

index.html

{% for photo in all_gallery %} 
    <img src="{{ photo.image }}">
{% endfor %}

问题原因及修复方案

1. 路径配置混乱

代码中同时定义了app.config["UPLOAD_PATH"]和UPLOAD_PATH两个变量,路径指向不一致,导致文件保存路径与数据库存储路径不匹配,浏览器无法正确定位图片资源。

2. 静态文件路径生成错误

Flask访问静态文件需通过url_for('static', filename='路径')生成标准URL,直接使用存储的相对路径会导致解析错误。

具体修复步骤

步骤1:统一上传路径配置

修改main.py中的上传路径,确保文件保存到static/uploads目录,并自动创建该目录:

# 替换原UPLOAD_PATH相关配置
app.config["UPLOAD_PATH"] = os.path.join(app.root_path, 'static', 'uploads')
# 自动创建uploads文件夹(不存在时)
os.makedirs(app.config["UPLOAD_PATH"], exist_ok=True)

步骤2:修正文件存储路径逻辑

上传时存储相对static目录的路径(如uploads/xxx.jpg),简化路径处理:

@app.route('/admin', methods=["GET", "POST"])
def index():
    gallery_form = GalleryForm()
    if gallery_form.validate_on_submit():
        new_gallery = Gallery()

        uploaded_file = gallery_form.image.data
        filename = secure_filename(uploaded_file.filename)
        # 生成文件保存路径
        save_path = os.path.join(app.config["UPLOAD_PATH"], filename)
        uploaded_file.save(save_path)
        # 存储相对static的路径,方便后续生成URL
        new_gallery.image = f"uploads/{filename}"

        db.session.add(new_gallery)
        db.session.commit()
        return redirect(url_for('index'))

    gallery_image = db.session.execute(db.select(Gallery)).scalars().all()
    return render_template("index.html", all_gallery=gallery_image, gallery_form=gallery_form)

步骤3:修正HTML中的图片URL生成

在index.html中使用Flask的url_for函数生成正确的静态文件访问地址:

{% for photo in all_gallery %} 
    <img src="{{ url_for('static', filename=photo.image) }}" alt="Gallery Image">
{% endfor %}

额外检查项

  • 确认static/uploads目录存在且拥有读写权限
  • 检查数据库gallery表的image字段存储路径格式是否为uploads/xxx.jpg
  • 启动Flask后,直接访问http://localhost:5000/static/uploads/xxx.jpg测试图片能否正常打开

内容的提问来源于stack exchange,提问作者Talat Mahmud Osman Goni

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.26 21:47:34