Yii2实现UploadedFile上传文件示例
程序员文章站
2024-03-13 20:28:39
闲来无事,整理了一下自己写的文件上传类。
通过
uploadfile::getinstance($model, $attribute);
uploadfi...
闲来无事,整理了一下自己写的文件上传类。
通过
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中的键值作为参数传递到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方法,通过递归把$_files中的内容保存到 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, ]); } }
实例:
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());
对应的 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 */ //通过php的move_uploaded_file() 方法保存临时文件为目标文件 public function saveas($file, $deletetempfile = true) { //$this->error == upload_err_ok upload_err_ok 其值为 0,没有错误发生,文件上传成功。 if ($this->error == upload_err_ok) { if ($deletetempfile) { //将上传的文件移动到新位置 return move_uploaded_file($this->tempname, $file); } elseif (is_uploaded_file($this->tempname)) {//判断文件是否是通过 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 */ //获取上传文件扩展名称 "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. */ //上传文件是否出现错误 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, ]; } } }
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。