Flask——檔案上傳

codelife發表於2019-08-24

匯入所需模組

from app.admin import admin
import os
from flask import Flask, request, redirect, url_for
from werkzeug import secure_filename
from app import app

定義修改檔名函式

def change_filename(filename):
    filename = os.path.splitext(filename)
    new_file = time.strftime('%Y%m%d%H%M%S', time.localtime())+str(uuid.uuid4().hex)+filename[-1]
    return new_file

在配置項中新增配置

#允許上傳檔案字尾名
ALLOWED_EXTENSIONS = set(['txt', 'pdf', 'png', 'jpg', 'jpeg', 'gif'])
#檔案儲存目錄
UP_DIR = os.path.join(os.path.abspath(os.path.dirname(__file__)), 'app/static/admin/uploads/')

過濾不允許上傳檔案

def allowed_file(filename):
    return '.' in filename and filename.rsplit('.', 1)[1] in ALLOWED_EXTENSIONS

上傳方法

@admin.route('/upload', methods=['POST'])
def upload_file():
    file = request.files.get('file')
    if file and allowed_file(file.filename):
        filename = secure_filename(file.filename)
    if not os.path.exists(app.config['UP_DIR']):
        os.makedirs(app.config['UP_DIR'],755)
        filename = change_filename(filename)
        file.save(os.path.join(app.config['UP_DIR'], filename))
本作品採用《CC 協議》,轉載必須註明作者和本文連結

相關文章