Deprecated: imwpcache\f884414bce24ee67f\f73723ec7b1919fa5::__construct(): Implicitly marking parameter $YECBGYFECGEAFWHA as nullable is deprecated, the explicit nullable type must be used instead in /www/wwwroot/www.chuangxiangniao.com/wp-content/plugins/imwpcache-dist/build/f884414bce24ee67ff73723ec7b1919fa5.php on line 2

Deprecated: imwpcache\f884414bce24ee67f\f73723ec7b1919fa5::__construct(): Implicitly marking parameter $BBWFDDBHHYHDXXAB as nullable is deprecated, the explicit nullable type must be used instead in /www/wwwroot/www.chuangxiangniao.com/wp-content/plugins/imwpcache-dist/build/f884414bce24ee67ff73723ec7b1919fa5.php on line 2
在 Flask 中实现多张图片上传并同时显示_创想鸟

在 Flask 中实现多张图片上传并同时显示

在 flask 中实现多张图片上传并同时显示

在 Flask 应用中实现多张图片上传并同时显示的功能,关键在于正确管理每个上传文件的状态,避免覆盖。以下将详细介绍如何通过结合 Flask 的 session 功能,简化 Python 代码和 HTML 模板,使得多个图片可以独立上传和显示。

使用 Flask Session 管理图片

Flask 的 session 对象允许你在用户会话期间存储数据。这非常适合用于保存上传文件的信息,以便在后续请求中访问。

1. 安装 Flask Session

首先,确保你已经安装了 Flask Session:

pip install Flask-Session

2. 配置 Flask Session

在你的 Flask 应用中,配置 session:

from flask import Flask, render_template, request, redirect, url_for, flash, sessionfrom flask_session import Sessionimport osfrom werkzeug.utils import secure_filenameapp = Flask(__name__)app.config['SECRET_KEY'] = 'your_secret_key'  # 替换为你自己的密钥app.config['UPLOAD_FOLDER'] = 'static/uploads'app.config["SESSION_PERMANENT"] = Falseapp.config["SESSION_TYPE"] = "filesystem"Session(app)ALLOWED_EXTENSIONS = {'png', 'jpg', 'jpeg', 'gif'}def allowed_file(filename):    return '.' in filename and            filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS@app.route('/')def home():    return render_template('index.html')@app.route('/', methods=['POST'])def upload_content():    if not any(f in ['content_file', 'style_file'] for f in request.files):        flash('No file part')        return redirect(request.url)    submitted_file = 'content_file' if 'content_file' in request.files else 'style_file'    file = request.files[submitted_file]    if file.filename == '':        flash('No image selected for uploading')        return redirect(request.url)    if file and allowed_file(file.filename):        filename = secure_filename(file.filename)        file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))        session[submitted_file] = filename        print('upload_image filename: ' + filename, os.path.join(app.config['UPLOAD_FOLDER'], filename))        flash('Image successfully uploaded and displayed below')        return render_template('index.html')    else:        flash('Allowed image types are - png, jpg, jpeg, gif')        return redirect(request.url)@app.route('/display/')def display_image(filename):    return redirect(url_for('static', filename='uploads/' + filename), code=301)if __name__ == '__main__':    os.makedirs(app.config['UPLOAD_FOLDER'], exist_ok=True) # Ensure upload folder exists    app.run(debug=True)

代码解释:

app.config[‘SECRET_KEY’]: 设置一个安全的密钥,用于加密 session 数据。请务必更换为你自己的密钥。app.config[‘UPLOAD_FOLDER’]: 指定上传文件保存的目录。Session(app): 初始化 Flask Session。upload_content() 函数:检查请求中是否包含 content_file 或 style_file。根据上传的文件类型,将其保存在 session 中。

3. 修改 HTML 模板

修改你的 HTML 模板(例如 index.html)以显示多个图片,并使用 session 中存储的文件名:

Select a content image to upload

{% with messages = get_flashed_messages() %} {% if messages %}

    {% for message in messages %}
  • {{ message }}
  • {% endfor %}
{% endif %} {% endwith %}

{% if session['content_file'] %} @@##@@ {% endif %}

Select a style image to upload

{% with messages = get_flashed_messages() %} {% if messages %}

    {% for message in messages %}
  • {{ message }}
  • {% endfor %}
{% endif %} {% endwith %}

{% if session['style_file'] %} @@##@@ {% endif %}

代码解释:

{% if session[‘content_file’] %} 和 {% if session[‘style_file’] %}: 检查 session 中是否存在相应的文件名,如果存在,则显示图片。 和 : 为每个文件上传字段使用不同的 name 属性。

总结

通过使用 Flask 的 session 功能,可以轻松地管理多个上传文件的状态,并在 HTML 模板中同时显示它们。这种方法避免了覆盖之前上传的文件,并且简化了代码结构。记住,为了安全起见,务必设置一个安全的 SECRET_KEY。此外,请确保在运行应用前创建 UPLOAD_FOLDER 目录。

在 Flask 中实现多张图片上传并同时显示在 Flask 中实现多张图片上传并同时显示

以上就是在 Flask 中实现多张图片上传并同时显示的详细内容,更多请关注创想鸟其它相关文章!

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 chuangxiangniao@163.com 举报,一经查实,本站将立刻删除。
发布者:程序猿,转转请注明出处:https://www.chuangxiangniao.com/p/1574559.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
本地开发Bootstrap组件:VS Code中引入CDN的正确姿势
上一篇 2025年12月22日 16:24:59
Flask HTML模板中渲染多张图片而不替换现有图片的方法
下一篇 2025年12月22日 16:25:15

相关推荐

发表回复

登录后才能评论
关注微信