tp与yii图片上传(layui)

html代码



  

js代码

tp后台方法

 public function upload()
    {
        $file = request()->file('file');
        // 移动到框架应用根目录/public/uploads/ 目录下
        if($file){
            $info = $file->validate(['size'=>102400,'ext'=>'jpeg,jpg,png,gif])->move(ROOT_PATH . 'public' . DS . 'uploads');
            if($info){
                return json_encode(['code'=>1,'src'=>$info->getFilename()]);
            }else{
                // 上传失败获取错误信息
                return json_encode(['code'=>0,'msg'=>$file->getError()]);
            }
        }
    }

yii2后台方法

 public function actionUpload()
    {
        if (Yii::$app->request->isPost) {
            $file = UploadedFile::getInstanceByName('file');
            $datefilename = date('Ymd');
            $dir=Yii::getAlias('@webroot').'/upload/'.$datefilename .'/';
            if(!file_exists($dir)) {
                mkdir($dir,0777,true);
            }
            //获得文件扩展名
            $temp_arr = explode(".", $file->name);
            $file_ext = array_pop($temp_arr);
            $file_ext = trim($file_ext);
            $file_ext = strtolower($file_ext);
            $new_file_name = date("YmdHis") . '_' . rand(10000, 99999) . '.' . $file_ext;
            $name =Yii::getAlias('@webroot').'/upload/'.$datefilename .'/'.$new_file_name;
            $status = $file->saveAs($name,true);
            if($status){
                $res = [
                    'src'=>'/upload/'.$datefilename .'/'.$new_file_name,
                    'code'=>1
                ];
            }else{
                $res =[
                    'code'=>0,
                    'msg'=>'上传失败!'
                ];
            }
            return json_encode($res);
        }

    }

你可能感兴趣的:(yii2,thinkphp,uploadimage)