回到首页

Flask框架实现文件上传功能

flask_upload项目,主目录下app.py

from flask import Flask, render_template, request
import os

app = Flask(__name__)
app.config['UPLOAD_FOLDER']='upload/'

@app.route('/')
def index():
    return render_template('index.html')

@app.route('/upload')
def upload_file():
    return render_template('upload.html')

@app.route('/uploader', methods=['GET', 'POST'])
def uploader():
    if request.method == 'POST':
        f = request.files['file']
        f.save(os.path.join(app.config['UPLOAD_FOLDER'], f.filename))
        print(f'file {f.filename} uploaded successfully')
        return render_template('upload.html')
    else:
        return render_template('upload.html')

@app.route('/tell', methods=['POST'])
def tell():
    print(request.form['words'])
    return render_template('index.html')

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

新建upload目录

templates/upload.html

<html>
    <head>
        <title>File Upload</title>
        <meta name="viewport" content="width=device-width, initial-scale=1.0"/>
    </head>
    <body>
        <form action="/uploader" method="POST" enctype="multipart/form-data">
            <input type="file" name="file"/>
            <input type="submit" value="提交"/>
        </form>
    </body>
</html>

templates/index.html

<html>
    <head>
        <title>index</title>
        <meta name="viewport" content="width=device-width, initial-scale=1.0"/>
    </head>
    <body>
        <ul><a href="/upload">上传文件</a></ul>
        <form method="post" action="/tell">
            <input type="text" name="words"/><br/>
            <button type="submit">提交</button>
        </form>
    </body>
</html>

python app.py运行上传文件项目,手机端也可使用

参考链接:Flask 文件上传

本文创建于2021年 08月 01日 星期日 12:24:07 CST,修改于2023.2.12/0.7