0
点赞
收藏
分享

微信扫一扫

flask文件上传到指定目录

天蓝Sea 2022-01-20 阅读 37

.py文件

from flask import Flask, render_template, request
from werkzeug.utils import secure_filename

import os

app = Flask(__name__)
""文件保存的目录,要根据自己的文件结构做相应的调整,
若不指定目录,可以这样写f.save(f.filename),这样就默认保存到当前文件夹下的根目录""

app.config['UPLOAD_FOLDER'] = 'study/flask/upload'

@app.route('/upload')
def upload_file():
    return render_template('upload.html')#渲染html文件

@app.route('/uploader',methods=['GET','POST'])
def uploader():
    if request.method == 'POST':
        f = request.files['file']
        print(request.files)
        f.save(os.path.join(app.config['UPLOAD_FOLDER'], secure_filename(f.filename)))

        return 'file uploaded successfully'

    else:

        return render_template('upload.html')

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

upload.html文件,放在templates目录文件夹下

<html>
<head>
<title>File Upload</title>
</head>
<body>
 <h1 align="center">xxxxxxxxxxxxxx</h1>
 <form action="http://localhost:5000/uploader" method="POST" enctype="multipart/form-data">
     <input type="file" name="file"  />
     <input type="submit" value="提交" />
 </form>
</body>
</html>

运行.py文件,访问http://localhost:5000/uploader,即可上传文件

文件目录结构
在这里插入图片描述

举报

相关推荐

0 条评论