31 lines
1.2 KiB
Python
31 lines
1.2 KiB
Python
import os
|
||
from werkzeug.utils import secure_filename
|
||
import datetime
|
||
import random
|
||
|
||
basedir = os.path.abspath(os.path.dirname(__file__))
|
||
ALLOWED_EXTENSIONS = set(['png', 'PNG', 'jpg', 'JPG', 'jpeg', 'gif', 'GIF'])
|
||
def allowed_file(filename):
|
||
return '.' in filename and filename.rsplit('.', 1)[1] in ALLOWED_EXTENSIONS
|
||
|
||
def create_uuid(): #生成唯一的图片的名称字符串,防止图片显示时的重名问题
|
||
nowTime = datetime.datetime.now().strftime("%Y%m%d%H%M%S") # 生成当前时间
|
||
randomNum = random.randint(0, 100) # 生成的随机整数n,其中0<=n<=100
|
||
if randomNum <= 10:
|
||
randomNum = str(0) + str(randomNum)
|
||
uniqueNum = str(nowTime) + str(randomNum)
|
||
return uniqueNum
|
||
|
||
def upload_photo(request):
|
||
file_dir = os.path.join(basedir, '../upload')
|
||
if not os.path.exists(file_dir):
|
||
os.makedirs(file_dir)
|
||
f = request.files['photo']
|
||
if f and allowed_file(f.filename):
|
||
fname = secure_filename(f.filename)
|
||
ext = fname.rsplit('.', 1)[1]
|
||
new_filename = create_uuid() + '.' + ext
|
||
f.save(os.path.join(file_dir, new_filename))
|
||
return {'errcode': 200, 'filename': new_filename}
|
||
else:
|
||
return {'errcode': 380, 'errmsg': '图片格式不符'} |