Use simple file upload flask

Import the Flask Flask from, the redirect, the render_template, Request, the url_for 
from werkzeug.utils Import secure_filename
Import OS
App = the Flask (__ name__)
ALLOWED_EXTENSIONS = SET ([ 'TXT', 'PDF', 'PNG', 'JPG', 'JPEG' , 'GIF', 'DOC'])

# setting allows file uploads type


DEF allowed_file (filename):
"" "
file type uploaded
: param filename: incoming file name
: return: return True or False
" ""
filename.rsplit filename and in return (,. 1 ".") [. 1] in ALLOWED_EXTENSIONS. ""


@ app.route ( "/", Methods = [ "the GET", "the POST"])
DEF file_name ():
"" "
Upload file
: return:Return to the upload file url address
"" "
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():
"""
The view function of the file type does not match
: return:
"" "
return" file does not conform to the rules "


IF the __name__ == '__main__':
app.run (Debug = True)

Guess you like

Origin www.cnblogs.com/666666pingzi/p/11210942.html