Stories

Detail Return Return

Yii 使用gargron/fileupload插件實現上傳文件 - Stories Detail

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());
    }
}

根據如上代碼可以實現文件上傳

user avatar me_life Avatar liujiaxiaobao Avatar fecify Avatar
Favorites 3 users favorite the story!
Favorites

Add a new Comments

Some HTML is okay.