【转】Flask入门之上传文件到服务器

#Sample.py

# 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__)  # 当前文件所在路径
        upload_path = os.path.join(basepath, 'staticuploads',secure_filename(f.filename))  #注意:没有的文件夹一定要先创建,不然会提示没有该路径
        f.save(upload_path)
        return redirect(url_for('upload'))
    return render_template('upload.html')

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

#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>

这里要注意:<form>标签里的enctype属性一定要填写'multipart/form-data'

意思是不加密,上传文件的时候一定要选这个,不然不行

好了接下来我们看看运行效果

1. 初始界面

2. 选择一个文件,点击上传

 3. 最后网页会回到初始界面,然后上传的文件,也保存在我们指定的目录上了

至此,项目结束

原文地址:https://www.cnblogs.com/wongbingming/p/6802660.html

原文地址:https://www.cnblogs.com/mqxs/p/10199726.html