使用flask實現簡單的文件上傳


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)


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM