zoukankan      html  css  js  c++  java
  • falsk之文件上传

    在使用flask定义路由完成文件上传时,定义upload视图函数

    from flask import Flask, render_template
    from werkzeug.utils import secure_filename
    import os
    
    app = Flask(__name__)
    app.debug = True
    app.secret_key = 'helloworld!!'
    
    @app.route('/')
    def hello_world():
        return 'Hello World!'
    
    @app.route('/upload',methods=['GET','POST'])
    def upload():
        if request.method == 'POST':
            f = request.files['file']
            base_path = os.path.abspath(os.path.dirname(__file__))
            upload_path = os.path.join(base_path,'staticuploads')
            f.save(upload_path,secure_filename(f.filename))
            return "文件上传成功!!"
        return render_template('upload.html')
    
    @app.errorhandler(404)
    def page_not_found(error):
        return render_template('404.html'),404
    
    if __name__ == '__main__':
        app.run(debug=True)

    upload.html前端页面的内容为

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>文件上传</title>
    </head>
    <body>
    <h1>文件上传示例</h1>
    <form action="" method="post" enctype="multipart/form-data">
        <input type="file" name="file">
        <input type="submit" value="上传">
    </form>
    </body>
    </html>

    启动项目,用浏览器打开http://127.0.0.1:5000/upload页面,前端页面显示如图所示

    选择要上传的文件

    文件选择完毕后,点击上传,flask会抛出异常,提供没有权限

    修改upload视图函数

    @app.route('/upload',methods=['GET','POST'])
    def upload():
        if request.method == 'POST':
            f = request.files['file']
            base_path = os.path.abspath(os.path.dirname(__file__))
            upload_path = os.path.join(base_path,'staticuploads',secure_filename(f.filename))
            f.save(upload_path)
            return "文件上传成功!!"
        return render_template('upload.html')

    再次进行文件上传,选中文件后,点击上传按钮,可以看到

    由此可以看出,文件已经成功上传,此时查看项目static/uploads目录,可以看到上传的图片已经保存在flask项目中了

    由此可以在Flask项目中完成文件上传功能!!

  • 相关阅读:
    底图与蒙版的过渡效果transition
    消除blur属性的边框
    jquery ajax实例教程和一些高级用法
    常用js正则表达式大全
    HTML5 + JS 调取摄像头拍照下载
    JS运动框架
    JS 实现AJAX封装(只限于异步)
    事件委托详解
    JS 实现随机验证码功能
    利用JS调取电脑摄像头,实现拍照功能
  • 原文地址:https://www.cnblogs.com/sui776265233/p/9893551.html
Copyright © 2011-2022 走看看