# URL: /api/portrait/upload
# 上传头像
class ApiPortraitUploadHandler(BaseHandler):
@login_required()
def post(self):
# 获取当前图片的名称
imgN = self.get_argument('imgN')
imgE = self.get_argument('imgE')
imgFile = os.path.realpath(os.path.join(os.path.dirname(__file__),
"../static/uploads/portrait/tmp",imgN)+imgE)
if os.path.exists(imgFile):
os.remove(imgFile) #删除用户切换的大图片
upload_dir = os.path.realpath(os.path.join(os.path.dirname(__file__),
"../static/uploads/portrait/tmp"))
random_name = str(uuid.uuid4())
# input 名字一定是"fileupload"
file_data = self.request.files["fileupload"][0]
original_name = file_data['filename']
extension = os.path.splitext(original_name)[1].lower()
if extension not in ['.png','.jpg','.gif']:
self.write({'code':'err',
'msg':u'只允许上传png,jpg,gif格式的图片,你上传的格式是: %s'%extension})
return
final_name = random_name + extension
final_path = os.path.join(upload_dir,final_name)
file_length = len(file_data['body'])
output_file = open(final_path, 'w')
output_file.write(file_data['body'])
output_file.close()
# relative_path = "%d/%s" % (self.current_user.id,final_name)
relative_path = "/static/uploads/portrait/tmp/%s" % (final_name)
result = {'name':random_name, 'ext':extension,'path':relative_path }
# without this header IE non-drag/drop upload will fail
self.set_header("Content-Type", "text/plain")
djson = {'code':'ok','uploads':result}
self.write(djson)
# URL: /api/portrait/save
# 保存头像
class ApiPortraitSaveHandler(BaseHandler):
@login_required()
def post(self):
imgN = self.get_argument('imgN')
imgE = self.get_argument('imgE')
imgP = self.get_argument('imgP')
imgT = int(self.get_argument('imgT'))
imgL = int(self.get_argument('imgL'))
imgW = int(self.get_argument('imgW'))
imgH = int(self.get_argument('imgH'))
imgP = os.path.realpath(os.path.join(os.path.dirname(__file__),
'..')+imgP)
imgNewN = imgN
if imgNewN == 'touxiang':
imgNewN = str(uuid.uuid4())
im = Image.open(imgP) #打开图片句柄
box = (imgL,imgT,(imgW+imgL),(imgH+imgT)) #设定裁剪区域
region = im.crop(box) #裁剪图片,并获取句柄region
imgPSave = os.path.realpath(os.path.join(os.path.dirname(__file__),
'..','static','uploads','portrait',imgNewN)+imgE)
# remove picture
if os.path.exists(imgP) and imgN != 'touxiang':
os.remove(imgP) #保存之前删除此图片的大图
userInfo = json.loads(self.current_user.info)
if userInfo.has_key('portrait'):
imgPBefore = os.path.realpath(os.path.join(os.path.dirname(__file__),
'..','static','uploads','portrait',userInfo['portrait']))
if os.path.exists(imgPBefore) :
os.remove(imgPBefore) #保存之前删除用户之前用的图片
region.save(imgPSave) #保存图片
if not userInfo.has_key('portrait') or userInfo['portrait'] != (imgNewN+imgE):
userInfo['portrait'] = imgNewN + imgE
self.current_user.info = json.dumps(userInfo)
self.db.commit()
self.write({'code':'ok'})