前端javascript:
$('#upfile').change(function(e){
var file = this.files[0];
var type = file.type.split('/')[1];
if(type != 'jpg' && type != 'jpeg' && type != 'png' && type != 'gif'){
$(this).parent('form')[0].reset();
errmsg('上传头像的格式必须为jpg,png或gif!');
return;
}
if(file.size > 2097152){
$(this).parent('form')[0].reset();
errmsg('头像大小不得超过2M,请重新上传');
return;
}
var formData = new FormData();
formData.append('file', this.files[0]);
var $lay, $index;
$.ajax({
url: "upload",
type: "POST",
dataType : 'JSON',
data: formData,
processData: false, // 告诉jQuery不要去处理发送的数据
contentType: false, // 告诉jQuery不要去设置Content-Type请求头
beforeSend : function(){
layer.msg("正在上传...", {
icon : 16,
time : 0,
shade : 0.2,
success : function(lay, index){
$lay = lay;
$index = index;
}
});
},
success : function(resp){
setTimeout(function(){
var html = '<i class="layui-layer-ico layui-layer-ico'+(resp.errcode == 0 ? 1 : 2)+'"></i>'+resp.errmsg;
$lay.children('.layui-layer-content').html(html);
setTimeout(function(){
layer.close($index);
}, 1500);
}, 1000);
if(resp.errcode == 0){
$('#face').attr('src', resp.logo);
}
}
});
php处理的upload方法:
public function actionUpload(){
if(!Yii::$app->getSession()->has('user_id')){
JsonHelper::ajaxSend(1, '请先登录!');
}
$uid = 0;
if(self::existSession('user_id')){
$uid = self::getSession('user_id');
}else if(self::existCookie('user_id')){
$uid = self::getCookie('user_id');
}
$res = NewsUsers::find()->where(['user_id' =>$uid])->one();
if(empty($res)){
JsonHelper::ajaxSend(2, '用户不存在!');
}
if(empty($_FILES['file'])){
JsonHelper::ajaxSend(3, '上传头像不能为空');
}
if($_FILES['file']['error'] != 0){
JsonHelper::ajaxSend(4, '上传图片出错!请重新上传!');
}
if($_FILES['file']['size'] == 0){
JsonHelper::ajaxSend(5, '上传图片大小为0');
}
if($_FILES['file']['size'] > 2097152){
JsonHelper::ajaxSend(6, '头像大小不得超过2M,请重新上传');
}
$image = $_FILES['file'];
$type = FileHelper::getFileRealType($image['tmp_name']);
if(!in_array($type, ['jpg', 'jpeg', 'png', 'gif'])){
JsonHelper::ajaxSend(7, '上传头像格式必须为jpg、png或gif!');
}
$info = BaseUserHelper::createProfile($image, $res['logo']);
if($info['errcode'] != 0){
JsonHelper::ajaxSend(8, $info['errmsg']);
}
$res->logo = $info['logo'];
if(!$res->save(false)){
JsonHelper::ajaxSend(9, '上传头像失败');
}
$result = JsonHelper::setErrMsg(0, '上传头像成功');
$result['logo'] = UserHelper::getUserLogo($info['logo']);
JsonHelper::ajaxSend($result);
}