zoukankan      html  css  js  c++  java
  • flask上传文件到指定路径

    flask上传文件到指定路径

    项目结构如下:

    首先是:视图函数uload_file.py,代码如下:

    #!/usr/bin/env python
    # -*- coding: utf-8 -*-
    
    from flask import Flask,render_template,request,redirect,url_for
    from werkzeug.utils import secure_filename
    import os
    
    app = Flask(__name__)
    
    @app.route('/upload', methods=['POST', 'GET'])
    def upload():
        if request.method == 'POST':
            f = request.files['file']
            basepath = os.path.dirname(__file__)  # 当前文件所在路径
            print(basepath)
            upload_path = os.path.join(basepath, 'upload_file_dir',secure_filename(f.filename))
            # 注意:没有的文件夹一定要先创建,不然会提示没有该路径
            print(upload_path)
            upload_path = os.path.abspath(upload_path) # 将路径转换为绝对路径
            print(upload_path)
            f.save(upload_path)
            return redirect(url_for('upload'))
        return render_template('upload.html')
    
    
    if __name__ == '__main__':
        app.run(debug=True)

    然后是html模板:upload.html

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

    最后可以发现已经成功上传

  • 相关阅读:
    Lua环境
    WebKit
    Net线程间通信的异步机制
    Cucumber入门1 传统流程下的使用
    Windows Server 2008中安装IIS7.0
    WebCore
    百度云计算平台Python环境试用
    认识ASP.NET MVC的5种AuthorizationFilter
    浅谈java中常见的排序
    go语言中goroutine的使用
  • 原文地址:https://www.cnblogs.com/111testing/p/10810088.html
Copyright © 2011-2022 走看看