在使用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页面,前端页面显示如图所示

falsk之文件上传

选择要上传的文件

falsk之文件上传

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

falsk之文件上传

修改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')

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

falsk之文件上传

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

falsk之文件上传

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

 

相关文章:

  • 2022-01-07
  • 2021-12-14
  • 2021-04-18
  • 2021-12-01
  • 2021-10-30
  • 2021-09-29
  • 2021-06-01
  • 2021-12-10
猜你喜欢
  • 2022-12-23
  • 2022-12-23
  • 2021-08-02
  • 2021-05-24
  • 2021-05-21
  • 2021-12-04
相关资源
相似解决方案