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

Flask网站仅显示图片文件图标问题排查求助

问题:网站仅显示图片文件图标故障排查与解决

问题背景

网站提交表单后仅显示图片文件图标,无法正常加载图片,相关核心代码、模板文件、终端日志如下:

核心Flask代码

@app.route("/index.html", methods=["GET", "POST"])
def index():
    if request.method == "POST":
        user_input = request.form.get("user_input")
        return render_template("image.html", user_input=user_input)
    else:
        return render_template("index.html")


@app.route("/generate_image/<string:user_string>")
def generate_image(user_string):

    #select one of the example images
    num = randint(1, 8)
    image = Image.open(f"./pics/{num}.jpeg")
    
    # Create a new response object and set the content type to "image/png"
    response = make_response(image.tobytes())
    response.headers.set('Content-Type', 'image/jpeg')
    
    # Return the response to the user
    return response

image.html模板内容

<img src={{ url_for('generate_image', user_string=user_input) }}>

终端输出日志

127.0.0.1 - - [24/Apr/2023 21:49:10] "GET / HTTP/1.1" 200 -
127.0.0.1 - - [24/Apr/2023 21:49:10] "GET /static/styles.css HTTP/1.1" 200 -
127.0.0.1 - - [24/Apr/2023 21:49:10] "GET /static/favicon.ico HTTP/1.1" 404 -
127.0.0.1 - - [24/Apr/2023 21:49:13] "POST /index.html HTTP/1.1" 200 -
127.0.0.1 - - [24/Apr/2023 21:49:13] "GET /static/styles.css HTTP/1.1" 200 -
127.0.0.1 - - [24/Apr/2023 21:49:13] "GET /static/favicon.ico HTTP/1.1" 404 -
127.0.0.1 - - [24/Apr/2023 21:49:13] "GET /generate_image/thing HTTP/1.1" 200 -

已知文件夹结构正确,pics文件夹与Python文件同目录,尝试多个调试工具未解决问题。

故障原因

直接返回image.tobytes()仅输出了图片的原始像素数据,缺少JPEG格式的编码头信息,浏览器无法识别这些原始数据为有效的JPEG图片,因此显示文件图标而非正常加载图片。

解决方法

修改generate_image函数,将图片以JPEG格式编码后再返回,而非直接返回原始字节:

# 需提前导入io模块
import io

@app.route("/generate_image/<string:user_string>")
def generate_image(user_string):
    num = randint(1, 8)
    image = Image.open(f"./pics/{num}.jpeg")
    
    # 创建字节流对象,将图片以JPEG格式写入
    img_byte_arr = io.BytesIO()
    image.save(img_byte_arr, format='JPEG')
    img_byte_arr.seek(0)  # 将指针移到流开头
    
    response = make_response(img_byte_arr.getvalue())
    response.headers.set('Content-Type', 'image/jpeg')
    return response

同时修正模板中的img标签,符合HTML规范:

<img src="{{ url_for('generate_image', user_string=user_input) }}" alt="随机图片">

内容的提问来源于stack exchange,提问作者Ablaze

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.24 02:57:31