导入所需模块
~~~
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=['GET', 'POST'])
def upload_file():
if request.method == 'POST':
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))
return redirect(url_for('uploaded_file',
filename=filename))
~~~