<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title></title>
</head>
<body>
<form action="/upload" method="post" enctype="multipart/form-data">
<input type="file" name="uimg">
<input type="submit" value="Login" >
</form>
</body>
</html>
复制代码
注意:在下面的代码中我将上传后的图片进行了重命名。为了防止同名的文件会进行覆盖html
import os
import time, datetime
from flask import Flask, request, render_template
app = Flask(__name__)
@app.route('/upload', methods=["POST", "GET"])
def file_views():
if request.method == 'GET':
return render_template('upload/upload.html')
else:
# 获得上传的文件
f = request.files['uimg']
# 将文件保存到指定的目录处[相对路径](不推荐)
# f.save('static/' +f.filename)
# 将文件保存到指定的目录[绝对路径](推荐)
# 获取当前根目录所在的路径
basedir = os.path.dirname(__file__)
'''# 第一种方法使用time模块 today = os.path.join(basedir, 'static','upload', time.strftime('%Y%m%d')) if not os.path.exists(today): os.makedirs(today) now = time.strftime('%H%M%S') + os.path.splitext(f.filename)[1] upload_path = os.path.join(today, now) '''
# 第二种方法使用datetime模块
ftime = datetime.datetime.now().strftime('%Y%m%d%H%M%S%f')
ext = os.path.splitext(f.filename)[1]
upload_path = os.path.join(basedir, 'static', 'upload', ftime + ext)
f.save(upload_path)
return "save OK"
if __name__ == '__main__':
app.run(debug=True, host='0.0.0.0')
复制代码