上傳圖片

前端:
<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']];
        }
    }
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章