renpingsheng

在使用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,'static\uploads')
        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,'static\uploads',secure_filename(f.filename))
        f.save(upload_path)
        return "文件上传成功!!"
    return render_template('upload.html')

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

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

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

相关文章: