标签:上传图片 前台 后台
前端: <form action="/upload" method="post" enctype="multipart/form-data"> <img src="img/01.png" /> <input type="file" name="avatar" value="浏览"> <input type="submit" value="提交"> </form> 后台: namespace Cloud\Controller; use Cloud\Model, Pagination, Utils; class User extends Controller{ function modify(){ if($_FILES[‘avatar‘][‘name‘]){ # 有提交图片 $res = Utils::upload($_FILES[‘avatar‘]); if($res[‘code‘] != ‘3‘){ $this->body= $res[‘desc‘]; $this->render(); return false; } $_POST[‘avatar‘] = json_encode([‘type‘=>‘2‘,‘data‘=>‘http://xxx.com/‘.$res[‘url‘]]); }else{ unset($_POST[‘avatar‘]); } $_POST[‘appid‘] = ($_POST[‘appid‘]!=‘‘)?$_POST[‘appid‘]:null; Model::user()->update($_POST,[‘user_id‘=>$_POST[‘user_id‘]]); $this->redirect($this->url(‘view‘)); } } class Utils{ static function upload($file){ $name = $file[‘name‘]; $type = strtolower(substr($name,strrpos($name,‘.‘)+1)); $allow_type = array(‘jpg‘,‘jpeg‘,‘gif‘,‘png‘); if(!in_array($type, $allow_type)) return [‘code‘=>‘0‘,‘desc‘=>‘图片上传格式不对‘]; if(!is_uploaded_file($file[‘tmp_name‘])) return [‘code‘=>‘1‘,‘desc‘=>‘非法上传‘]; $upload_path = "img/"; if(!move_uploaded_file($file[‘tmp_name‘],$upload_path.$file[‘name‘])){ return [‘code‘=>‘2‘,‘desc‘=>‘图片上传失败‘]; }else{ return [‘code‘=>‘3‘,‘desc‘=>‘上传成功‘,‘url‘=>$upload_path.$file[‘name‘]]; } } }
标签:上传图片 前台 后台
原文地址:http://11873993.blog.51cto.com/11863993/1881464