Flask上传本地图片并在页面上显示

 

使用Flask远程上传图片到服务器,并把获取到的图片显示到前端页面上。

 

方法一

 

目录结构:

  • 'static/images' 文件夹用来存放上传过来的图片
  • ‘templates’文件夹下的两个html文件定义显示页面
  • upload_pictures.py 是工程代码

upload_pictures.py 代码:

# coding:utf-8

from flask import Flask, render_template, request, redirect, url_for, make_response,jsonify
from werkzeug.utils import secure_filename
import os
import cv2
import time

from datetime import timedelta

#设置允许的文件格式
ALLOWED_EXTENSIONS = set(['png', 'jpg', 'JPG', 'PNG', 'bmp'])

def allowed_file(filename):
    return '.' in filename and filename.rsplit('.', 1)[1] in ALLOWED_EXTENSIONS

app = Flask(__name__)
# 设置静态文件缓存过期时间
app.send_file_max_age_default = timedelta(seconds=1)


# @app.route('/upload', methods=['POST', 'GET'])
@app.route('/upload', methods=['POST', 'GET'])  # 添加路由
def upload():
    if request.method == 'POST':
        f = request.files['file']

        if not (f and allowed_file(f.filename)):
            return jsonify({"error": 1001, "msg": "请检查上传的图片类型,仅限于png、PNG、jpg、JPG、bmp"})

        user_input = request.form.get("name")

        basepath = os.path.dirname(__file__)  # 当前文件所在路径

        upload_path = os.path.join(basepath, 'static/images', secure_filename(f.filename))  # 注意:没有的文件夹一定要先创建,不然会提示没有该路径
        # upload_path = os.path.join(basepath, 'static/images','test.jpg')  #注意:没有的文件夹一定要先创建,不然会提示没有该路径
        f.save(upload_path)

        # 使用Opencv转换一下图片格式和名称
        img = cv2.imread(upload_path)
        cv2.imwrite(os.path.join(basepath, 'static/images', 'test.jpg'), img)

        return render_template('upload_ok.html',userinput=user_input,val1=time.time())

    return render_template('upload.html')


if __name__ == '__main__':
    # app.debug = True
    app.run(host='0.0.0.0', port=8987, debug=True)

 

upload.html 文件代码:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Flask上传图片演示</title>
</head>
<body>
    <h1>使用Flask上传本地图片并显示示例一</h1>
    <form action="" enctype='multipart/form-data' method='POST'>
        <input type="file" name="file" style="margin-top:20px;"/>
        <br>
        <i>请输入你当前的心情(开心、超开心、超超开心):</i>
        <input type="text" class="txt_input" name="name"  value="超超开心" style="margin-top:10px;"/>
        <input type="submit" value="上传" class="button-new" style="margin-top:15px;"/>
    </form>
</body>
</html>

upload_ok.html文件代码:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Flask上传图片演示</title>
</head>
<body>
    <h1>使用Flask上传本地图片并显示示例一</h1>
    <form action="" enctype='multipart/form-data' method='POST'>
        <input type="file" name="file" style="margin-top:20px;"/>
        <br>
        <i>请输入你当前的心情(开心、超开心、超超开心):</i>
        <input type="text" class="txt_input" name="name"  value="超超开心" style="margin-top:10px;"/>
        <input type="submit" value="上传" class="button-new" style="margin-top:15px;"/>
    </form>
    <h1>阁下的心情是:{{userinput}}!</h1>
    <img src="{{ url_for('static', filename= './images/test.jpg',_t=val1) }}" width="400" height="400" alt="你的图片被外星人劫持了~~"/>
</body>
</html>

直接运行 python upload_pictures.py 就行了,定义了端口号8987,在本机上访问 '127.0.0.1:8987/upload' ,出现以下界面:

点击'浏览' 并上传后,上传的图片保存到了 ‘static/images'目录下,显示结果:

 

方法二

 

目录结构:

目录文件介绍同方法一。

 

upload_pictures.py 代码:

# coding:utf-8

from flask import Flask,render_template,request,redirect,url_for,make_response,jsonify
from werkzeug.utils import secure_filename
import os
import cv2

from datetime import timedelta

#设置允许的文件格式
ALLOWED_EXTENSIONS = set(['png', 'jpg', 'JPG', 'PNG', 'bmp'])

def allowed_file(filename):
    return '.' in filename and filename.rsplit('.', 1)[1] in ALLOWED_EXTENSIONS

app = Flask(__name__)
# 设置静态文件缓存过期时间
app.send_file_max_age_default = timedelta(seconds=1)

@app.route('/upload', methods=['POST', 'GET'])  # 添加路由
def upload():
    if request.method == 'POST':
        f = request.files['file']

        if not (f and allowed_file(f.filename)):
            return jsonify({"error": 1001, "msg": "请检查上传的图片类型,仅限于png、PNG、jpg、JPG、bmp"})

        user_input = request.form.get("name")

        basepath = os.path.dirname(__file__)  # 当前文件所在路径

        upload_path = os.path.join(basepath, 'static/images',secure_filename(f.filename))  #注意:没有的文件夹一定要先创建,不然会提示没有该路径
        f.save(upload_path)

        image_data = open(upload_path, "rb").read()
        response = make_response(image_data)
        response.headers['Content-Type'] = 'image/png'
        return response

    return render_template('upload.html')

if __name__ == '__main__':
    # app.debug = True
    app.run(host = '0.0.0.0',port = 8987,debug= True)

upload.html 文件代码:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Flask上传图片演示</title>
</head>
<body>
    <h1>使用Flask上传本地图片并显示示例二</h1>
    <form action="" enctype='multipart/form-data' method='POST'>
        <input type="file" name="file" style="margin-top:20px;"/>
        <br>
        <i>请输入你当前的心情(开心、超开心、超超开心):</i>
        <input type="text" class="txt_input" name="name"  value="超超开心" style="margin-top:10px;"/>
        <input type="submit" value="上传" class="button-new" style="margin-top:15px;"/>
    </form>
</body>
</html>

运行 python upload_pictures.py ,端口号定义的是8987,在本机上访问 '127.0.0.1:8987/upload' ,出现以下界面:

点击'浏览' 并上传后,上传的图片保存到了 ‘static/images'目录下,显示结果:

方法二显示出来的图片覆盖了整个页面。

tips: 如果是在其他机器上访问,把127.0.0.1的IP换成服务器的IP就行了。

 

  • 63
    点赞
  • 259
    收藏
    觉得还不错? 一键收藏
  • 19
    评论
在Flash中加载外部SWF文件非常简单。首先,确保你已经打开了Flash软件,并新建一个项目。 在主舞台上插入一个“影片剪辑”对象,可以使用Ctrl+M快捷键。将此影片剪辑对象重命名为“loader”。 在“loader”影片剪辑的第一帧上,插入一个空白关键帧。 在第一个关键帧上打开“动作”面板,可以使用F9快捷键。在“动作”面板中输入以下代码来加载外部SWF文件: ``` var myLoader:Loader = new Loader(); var url:URLRequest = new URLRequest("external.swf"); // 替换为你要加载的外部SWF文件名 myLoader.load(url); addChild(myLoader); ``` 将“external.swf”替换为你要加载的外部SWF文件的路径和文件名。 之后,你可以为加载的SWF文件添加相应的事件监听器,以便在加载完成后执行一些操作。例如,你可以在加载完成后执行以下代码: ``` myLoader.contentLoaderInfo.addEventListener(Event.COMPLETE, onLoadComplete); function onLoadComplete(event:Event):void { trace("外部SWF文件加载完成"); // 在此处添加你想要执行的代码 } ``` 这样,当外部SWF文件加载完成后,控制台会输出“外部SWF文件加载完成”,你可以在注释部分添加你自己的代码,来处理加载完成后的操作。 最后,在主舞台上插入一个按钮,并给它命名为“loadButton”。为该按钮的“点击”事件添加以下代码: ``` loadButton.addEventListener(MouseEvent.CLICK, onClickLoad); function onClickLoad(event:MouseEvent):void { myLoader.load(url); } ``` 这样,当用户点击“loadButton”按钮时,SWF文件会重新加载。 完成以上步骤后,你就成功地在Flash中加载了外部SWF文件。你可以根据需要对加载完成后的外部SWF文件进行处理,例如显示、控制动画等。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 19
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值