flask文件上傳

html文件代碼以下

<!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>
複製代碼

upload文件代碼以下

注意:在下面的代碼中我將上傳後的圖片進行了重命名。爲了防止同名的文件會進行覆蓋html

  • 第一種方法使用time模塊進行了重命名,而且天天的圖片都新建了一個文件夾,這種方法以秒爲最小時間新建文件
  • 第二種方法使用datetime模塊進行了重命名,將全部的圖片存放在了static/upload文件夾下面,這種方法以毫秒爲時間新建文件
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')

複製代碼
相關文章
相關標籤/搜索