关于php:Yii-使用gargronfileupload插件实现上传文件

89次阅读

共计 1225 个字符,预计需要花费 4 分钟才能阅读完成。

gargron/fileupload 插件地址:https://packagist.org/package…

一:gargron/fileupload 插件装置

composer require gargron/fileupload

二:应用 gargron/fileupload 插件实现上传

// 设置上传文件格式
$magicFile = Yii::getAlias(FileHelper::$mimeMagicFile);
$mimeTypes = require($magicFile);
$allowExt = ['png', 'jpg'];
foreach ($allowExt as $ext) {if (isset($mimeTypes[$ext])) {$allowMimes[] = $mimeTypes[$ext];
    }
}
// 验证(最大文件大小 2MB,只有两个容许的 mime 类型)$validator = new \FileUpload\Validator\Simple('2M', $allowMimes);
$savePath = 'upload/';
// 判断是否存在上传目录,不存在创立目录
if (!is_dir($savePath)) {FileHelper::createDirectory($savePath);
}
// 上传文件
$pathresolver = new \FileUpload\PathResolver\Simple($savePath);
// The machine's filesystem
$filesystem = new \FileUpload\FileSystem\Simple();
// files 为上传控件的 name 名
$fileupload = new \FileUpload\FileUpload($_FILES['files'], $_SERVER);
// Adding it all together. Note that you can use multiple validators or none at all
$fileupload->setPathResolver($pathresolver);
$fileupload->setFileSystem($filesystem);
$fileupload->addValidator($validator);
// Doing the deed
list($files, $headers) = $fileupload->processAll();
foreach($files as $file){
    //Remeber to check if the upload was completed
    if ($file->completed) {echo $file->getRealPath();
        // Call any method on an SplFileInfo instance
        var_dump($file->isFile());
    }
}

依据如上代码能够实现文件上传

正文完
 0