from flask import Flask, redirect, render_template, request, url_for from werkzeug.utils import secure_filename import os app = Flask(__name__) ALLOWED_EXTENSIONS = set(['txt', 'pdf', 'png', 'jpg', 'jpeg', 'gif', 'doc']) # 设置允许上传的文件的类型 def allowed_file(filename): """ 上传的文件类型 :param filename: 传入的文件名 :return: 返回True 或者 False """ return "." in filename and filename.rsplit(".", 1)[1] in ALLOWED_EXTENSIONS @app.route("/", methods=["GET", "POST"]) def file_name(): """ 上传文件 :return: 返回上传文件的url地址 """ if request.method == "POST": f = request.files["file"] if f and allowed_file(f.filename): path = os.path.split(os.getcwd())[0] print(path) file = path+"/demo/templates/"+secure_filename(f.filename) print(file) f.save(file) return redirect("/uploads") else: return redirect(url_for("fail")) return render_template("file_name.html") @app.route("/uploads") def successful(): """ 设置返回路径的视图函数 :return: """ url = url_for("file_name") return '访问文件的路径:http://127.0.0.1:5000{}'.format(url) @app.route("/fail") def fail(): """ 文件类型不符合的视图函数 :return: """ return "文件不符合规则" if __name__ == '__main__': app.run(debug=True)