美文网首页
yii2文件上传

yii2文件上传

作者: 我的楼兰0909 | 来源:发表于2018-12-13 22:18 被阅读0次
    use yii\web\UploadedFile;
    public function uploadFile($filename,$target_path='base',$type_allow=[],$size_max=8388608){
                if(empty($type))
                {
                    $type_allow=[
                        'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',//xlsx
                        'application/vnd.ms-excel',//xls
                        'image/jpeg',//jpg/jpeg
                        'image/png',//png
                        'image/gif'//gif
                    ];
                }
     
                $file = UploadedFile::getInstanceByName($filename);
                //查看文件是否上传到临时路径
                if(!$file->hasError)
                {
                    //$original_name = $file->baseName();//原文件名
                    //$realPath = $file->tempName;//临时文件的绝对路径
     
                    $ext = $file->getExtension();//扩展名
     
                    //判断文件类型
                    $type = $file->type;//文件类型
                    if(!in_array($type,$type_allow)) return ['code'=>'failure','error_msg'=>'文件类型不对'];
     
                    //判断文件大小
                    $size = $file->size;
                    if($size>$size_max) return ['code'=>'failure','error_msg'=>'文件太大'];
     
                    $filename = date('YmdHis').'-'.uniqid().'.'.$ext;
                    $basePath = Yii::$app->basePath;//项目根目录
                    $path = $basePath.'/uploads/'.$target_path;
                    if (!file_exists($path)) {
                        mkdir($path, 0777);
                        chmod($path, 0777);
                    }
                    $saveAs = $file->saveAs($path. '/' . $filename);
                    if($saveAs)
                    {
                        return [
                            'code'         => 'successful',               //状态
                            'filename'     => $filename,                  //文件名
                            'path_name'    => 'uploads/'.$target_path.'/'.$filename, //相对路径文件名
                            'fullpath_name'=> $path.'/'.$filename,        //全路径文件名
                        ];
                    }
                    else {
                        return ['code'=>'failure','error_msg'=>'文件上传异常'];
                    }
                }
                else{
                    return ['code'=>'failure','error_msg'=>'文件上传失败'];
                }
     
            }
    

    相关文章

      网友评论

          本文标题:yii2文件上传

          本文链接:https://www.haomeiwen.com/subject/qtyzcqtx.html