Yii2實(shí)現(xiàn)UploadedFile上傳文件示例
閑來(lái)無(wú)事,整理了一下自己寫(xiě)的文件上傳類。
通過(guò)
UploadFile::getInstance($model, $attribute); UploadFile::getInstances($model, $attribute); UploadFile::getInstanceByName($name); UploadFile::getInstancesByName($name);
把表單上傳的文件賦值到 UploadedFile中的 private static $_files 中
/** * Returns an uploaded file for the given model attribute. * The file should be uploaded using [[\yii\widgets\ActiveField::fileInput()]]. * @param \yii\base\Model $model the data model * @param string $attribute the attribute name. The attribute name may contain array indexes. * For example, '[1]file' for tabular file uploading; and 'file[1]' for an element in a file array. * @return UploadedFile the instance of the uploaded file. * Null is returned if no file is uploaded for the specified model attribute. * @see getInstanceByName() */ public static function getInstance($model, $attribute) { $name = Html::getInputName($model, $attribute); return static::getInstanceByName($name); } /** * Returns all uploaded files for the given model attribute. * @param \yii\base\Model $model the data model * @param string $attribute the attribute name. The attribute name may contain array indexes * for tabular file uploading, e.g. '[1]file'. * @return UploadedFile[] array of UploadedFile objects. * Empty array is returned if no available file was found for the given attribute. */ public static function getInstances($model, $attribute) { $name = Html::getInputName($model, $attribute); return static::getInstancesByName($name); } /** * Returns an uploaded file according to the given file input name. * The name can be a plain string or a string like an array element (e.g. 'Post[imageFile]', or 'Post[0][imageFile]'). * @param string $name the name of the file input field. * @return UploadedFile the instance of the uploaded file. * Null is returned if no file is uploaded for the specified name. */ public static function getInstanceByName($name) { $files = self::loadFiles(); return isset($files[$name]) ? $files[$name] : null; } /** * Returns an array of uploaded files corresponding to the specified file input name. * This is mainly used when multiple files were uploaded and saved as 'files[0]', 'files[1]', * 'files[n]'..., and you can retrieve them all by passing 'files' as the name. * @param string $name the name of the array of files * @return UploadedFile[] the array of UploadedFile objects. Empty array is returned * if no adequate upload was found. Please note that this array will contain * all files from all sub-arrays regardless how deeply nested they are. */ public static function getInstancesByName($name) { $files = self::loadFiles(); if (isset($files[$name])) { return [$files[$name]]; } $results = []; foreach ($files as $key => $file) { if (strpos($key, "{$name}[") === 0) { $results[] = $file; } } return $results; }
loadFiles()方法,把$_FILES中的鍵值作為參數(shù)傳遞到loadFilesRecursive($key, $names, $tempNames, $types, $sizes, $errors) 中
/** * Creates UploadedFile instances from $_FILE. * @return array the UploadedFile instances */ private static function loadFiles() { if (self::$_files === null) { self::$_files = []; if (isset($_FILES) && is_array($_FILES)) { foreach ($_FILES as $class => $info) { self::loadFilesRecursive($class, $info['name'], $info['tmp_name'], $info['type'], $info['size'], $info['error']); } } } return self::$_files; }
loadFilesRecursive方法,通過(guò)遞歸把$_FILES中的內(nèi)容保存到 self::$_files 中
/** * Creates UploadedFile instances from $_FILE recursively. * @param string $key key for identifying uploaded file: class name and sub-array indexes * @param mixed $names file names provided by PHP * @param mixed $tempNames temporary file names provided by PHP * @param mixed $types file types provided by PHP * @param mixed $sizes file sizes provided by PHP * @param mixed $errors uploading issues provided by PHP */ private static function loadFilesRecursive($key, $names, $tempNames, $types, $sizes, $errors) { if (is_array($names)) { foreach ($names as $i => $name) { self::loadFilesRecursive($key . '[' . $i . ']', $name, $tempNames[$i], $types[$i], $sizes[$i], $errors[$i]); } } elseif ($errors !== UPLOAD_ERR_NO_FILE) { self::$_files[$key] = new static([ 'name' => $names, 'tempName' => $tempNames, 'type' => $types, 'size' => $sizes, 'error' => $errors, ]); } }
實(shí)例:
html
<form class="form-horizontal form-margin50" action="<?= \yii\helpers\Url::toRoute('upload-face') ?>" method="post" enctype="multipart/form-data" id="form1"> <input type="hidden" name="_csrf" value="<?= Yii::$app->request->getCsrfToken() ?>"> <input type="file" name="head_pic" id="doc" style="display: none" onchange="setImagePreview()"/> </form>
php代碼,打印的
public static function uploadImage($userId = '', $tem = '') { $returnPath = ''; $path = 'uploads/headpic/' . $userId; if (!file_exists($path)) { mkdir($path, 0777); chmod($path, 0777); } $patch = $path . '/' . date("YmdHis") . '_'; $tmp = UploadedFile::getInstanceByName('head_pic'); if ($tmp) { $patch = $path . '/' . date("YmdHis") . '_'; $tmp->saveAs($patch . '1.jpg'); $returnPath .= $patch; } return $returnPath; }
打印dump($tmp,$_FILES,$tmp->getExtension());
對(duì)應(yīng)的 UploadedFile
class UploadedFile extends Object { /** * @var string the original name of the file being uploaded */ // "Chrysanthemum.jpg" public $name; /** * @var string the path of the uploaded file on the server. * Note, this is a temporary file which will be automatically deleted by PHP * after the current request is processed. */ // "C:\Windows\Temp\php8CEF.tmp" public $tempName; /** * @var string the MIME-type of the uploaded file (such as "image/gif"). * Since this MIME type is not checked on the server-side, do not take this value for granted. * Instead, use [[\yii\helpers\FileHelper::getMimeType()]] to determine the exact MIME type. */ // "image/jpeg" public $type; /** * @var integer the actual size of the uploaded file in bytes */ // 879394 public $size; /** * @var integer an error code describing the status of this file uploading. * @see http://www.php.net/manual/en/features.file-upload.errors.php */ // 0 public $error; private static $_files; /** * String output. * This is PHP magic method that returns string representation of an object. * The implementation here returns the uploaded file's name. * @return string the string representation of the object */ public function __toString() { return $this->name; } /** * Returns an uploaded file for the given model attribute. * The file should be uploaded using [[\yii\widgets\ActiveField::fileInput()]]. * @param \yii\base\Model $model the data model * @param string $attribute the attribute name. The attribute name may contain array indexes. * For example, '[1]file' for tabular file uploading; and 'file[1]' for an element in a file array. * @return UploadedFile the instance of the uploaded file. * Null is returned if no file is uploaded for the specified model attribute. * @see getInstanceByName() */ public static function getInstance($model, $attribute) { $name = Html::getInputName($model, $attribute); return static::getInstanceByName($name); } /** * Returns all uploaded files for the given model attribute. * @param \yii\base\Model $model the data model * @param string $attribute the attribute name. The attribute name may contain array indexes * for tabular file uploading, e.g. '[1]file'. * @return UploadedFile[] array of UploadedFile objects. * Empty array is returned if no available file was found for the given attribute. */ public static function getInstances($model, $attribute) { $name = Html::getInputName($model, $attribute); return static::getInstancesByName($name); } /** * Returns an uploaded file according to the given file input name. * The name can be a plain string or a string like an array element (e.g. 'Post[imageFile]', or 'Post[0][imageFile]'). * @param string $name the name of the file input field. * @return null|UploadedFile the instance of the uploaded file. * Null is returned if no file is uploaded for the specified name. */ public static function getInstanceByName($name) { $files = self::loadFiles(); return isset($files[$name]) ? new static($files[$name]) : null; } /** * Returns an array of uploaded files corresponding to the specified file input name. * This is mainly used when multiple files were uploaded and saved as 'files[0]', 'files[1]', * 'files[n]'..., and you can retrieve them all by passing 'files' as the name. * @param string $name the name of the array of files * @return UploadedFile[] the array of UploadedFile objects. Empty array is returned * if no adequate upload was found. Please note that this array will contain * all files from all sub-arrays regardless how deeply nested they are. */ public static function getInstancesByName($name) { $files = self::loadFiles(); if (isset($files[$name])) { return [new static($files[$name])]; } $results = []; foreach ($files as $key => $file) { if (strpos($key, "{$name}[") === 0) { $results[] = new static($file); } } return $results; } /** * Cleans up the loaded UploadedFile instances. * This method is mainly used by test scripts to set up a fixture. */ //清空self::$_files public static function reset() { self::$_files = null; } /** * Saves the uploaded file. * Note that this method uses php's move_uploaded_file() method. If the target file `$file` * already exists, it will be overwritten. * @param string $file the file path used to save the uploaded file * @param boolean $deleteTempFile whether to delete the temporary file after saving. * If true, you will not be able to save the uploaded file again in the current request. * @return boolean true whether the file is saved successfully * @see error */ //通過(guò)php的move_uploaded_file() 方法保存臨時(shí)文件為目標(biāo)文件 public function saveAs($file, $deleteTempFile = true) { //$this->error == UPLOAD_ERR_OK UPLOAD_ERR_OK 其值為 0,沒(méi)有錯(cuò)誤發(fā)生,文件上傳成功。 if ($this->error == UPLOAD_ERR_OK) { if ($deleteTempFile) { //將上傳的文件移動(dòng)到新位置 return move_uploaded_file($this->tempName, $file); } elseif (is_uploaded_file($this->tempName)) {//判斷文件是否是通過(guò) HTTP POST 上傳的 return copy($this->tempName, $file);//copy — 拷貝文件 } } return false; } /** * @return string original file base name */ //獲取上傳文件原始名稱 "name" => "Chrysanthemum.jpg" "Chrysanthemum" public function getBaseName() { // https://github.com/yiisoft/yii2/issues/11012 $pathInfo = pathinfo('_' . $this->name, PATHINFO_FILENAME); return mb_substr($pathInfo, 1, mb_strlen($pathInfo, '8bit'), '8bit'); } /** * @return string file extension */ //獲取上傳文件擴(kuò)展名稱 "name" => "Chrysanthemum.jpg" "jpg" public function getExtension() { return strtolower(pathinfo($this->name, PATHINFO_EXTENSION)); } /** * @return boolean whether there is an error with the uploaded file. * Check [[error]] for detailed error code information. */ //上傳文件是否出現(xiàn)錯(cuò)誤 public function getHasError() { return $this->error != UPLOAD_ERR_OK; } /** * Creates UploadedFile instances from $_FILE. * @return array the UploadedFile instances */ private static function loadFiles() { if (self::$_files === null) { self::$_files = []; if (isset($_FILES) && is_array($_FILES)) { foreach ($_FILES as $class => $info) { self::loadFilesRecursive($class, $info['name'], $info['tmp_name'], $info['type'], $info['size'], $info['error']); } } } return self::$_files; } /** * Creates UploadedFile instances from $_FILE recursively. * @param string $key key for identifying uploaded file: class name and sub-array indexes * @param mixed $names file names provided by PHP * @param mixed $tempNames temporary file names provided by PHP * @param mixed $types file types provided by PHP * @param mixed $sizes file sizes provided by PHP * @param mixed $errors uploading issues provided by PHP */ private static function loadFilesRecursive($key, $names, $tempNames, $types, $sizes, $errors) { if (is_array($names)) { foreach ($names as $i => $name) { self::loadFilesRecursive($key . '[' . $i . ']', $name, $tempNames[$i], $types[$i], $sizes[$i], $errors[$i]); } } elseif ((int)$errors !== UPLOAD_ERR_NO_FILE) { self::$_files[$key] = [ 'name' => $names, 'tempName' => $tempNames, 'type' => $types, 'size' => $sizes, 'error' => $errors, ]; } } }
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
- Yii中使用PHPExcel導(dǎo)出Excel的方法
- Yii2框架中使用PHPExcel導(dǎo)出Excel文件的示例
- Yii框架使用PHPExcel導(dǎo)出Excel文件的方法分析【改進(jìn)版】
- Yii Framework框架使用PHPExcel組件的方法示例
- YII2框架中excel表格導(dǎo)出的方法詳解
- Yii安裝與使用Excel擴(kuò)展的方法
- Yii框架擴(kuò)展CGridView增加導(dǎo)出CSV功能的方法
- Yii2使用自帶的UploadedFile實(shí)現(xiàn)的文件上傳
- Yii配置文件用法詳解
- Yii2中YiiBase自動(dòng)加載類、引用文件方法分析(autoload)
- YII中Ueditor富文本編輯器文件和圖片上傳的配置圖文教程
- Yii框架中使用PHPExcel的方法分析
相關(guān)文章
解決Laravel 使用insert插入數(shù)據(jù),字段created_at為0000的問(wèn)題
今天小編就為大家分享一篇解決Laravel 使用insert插入數(shù)據(jù),字段created_at為0000的問(wèn)題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2019-10-10laravel在中間件內(nèi)生成參數(shù)并且傳遞到控制器中的2種姿勢(shì)
今天小編就為大家分享一篇laravel在中間件內(nèi)生成參數(shù)并且傳遞到控制器中的2種姿勢(shì),具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2019-10-10php生成隨機(jī)密碼自定義函數(shù)代碼(簡(jiǎn)單快速)
創(chuàng)建大量用戶時(shí)一個(gè)一個(gè)想密碼是讓人頭疼的事,使用php隨機(jī)生成一個(gè)安全可靠的密碼,又方便又快捷,可以添加自己想的字符串,可以用在FTP密碼、Mysql密碼、網(wǎng)站后臺(tái)密碼等地方2014-05-05