查看: 1128|回复: 0

[PHP实例] Yii2实现UploadedFile上传文件示例

发表于 2017-12-12 08:00:01

闲来无事,整理了一下自己写的文件上传类。

通过

  1. UploadFile::getInstance($model, $attribute);
  2. UploadFile::getInstances($model, $attribute);
  3. UploadFile::getInstanceByName($name);
  4. UploadFile::getInstancesByName($name);
复制代码

把表单上传的文件赋值到 UploadedFile中的 private static $_files 中

  1. /**
  2. * Returns an uploaded file for the given model attribute.
  3. * The file should be uploaded using [[\yii\widgets\ActiveField::fileInput()]].
  4. * @param \yii\base\Model $model the data model
  5. * @param string $attribute the attribute name. The attribute name may contain array indexes.
  6. * For example, '[1]file' for tabular file uploading; and 'file[1]' for an element in a file array.
  7. * @return UploadedFile the instance of the uploaded file.
  8. * Null is returned if no file is uploaded for the specified model attribute.
  9. * @see getInstanceByName()
  10. */
  11. public static function getInstance($model, $attribute)
  12. {
  13. $name = Html::getInputName($model, $attribute);
  14. return static::getInstanceByName($name);
  15. }
  16. /**
  17. * Returns all uploaded files for the given model attribute.
  18. * @param \yii\base\Model $model the data model
  19. * @param string $attribute the attribute name. The attribute name may contain array indexes
  20. * for tabular file uploading, e.g. '[1]file'.
  21. * @return UploadedFile[] array of UploadedFile objects.
  22. * Empty array is returned if no available file was found for the given attribute.
  23. */
  24. public static function getInstances($model, $attribute)
  25. {
  26. $name = Html::getInputName($model, $attribute);
  27. return static::getInstancesByName($name);
  28. }
  29. /**
  30. * Returns an uploaded file according to the given file input name.
  31. * The name can be a plain string or a string like an array element (e.g. 'Post[imageFile]', or 'Post[0][imageFile]').
  32. * @param string $name the name of the file input field.
  33. * @return UploadedFile the instance of the uploaded file.
  34. * Null is returned if no file is uploaded for the specified name.
  35. */
  36. public static function getInstanceByName($name)
  37. {
  38. $files = self::loadFiles();
  39. return isset($files[$name]) ? $files[$name] : null;
  40. }
  41. /**
  42. * Returns an array of uploaded files corresponding to the specified file input name.
  43. * This is mainly used when multiple files were uploaded and saved as 'files[0]', 'files[1]',
  44. * 'files[n]'..., and you can retrieve them all by passing 'files' as the name.
  45. * @param string $name the name of the array of files
  46. * @return UploadedFile[] the array of UploadedFile objects. Empty array is returned
  47. * if no adequate upload was found. Please note that this array will contain
  48. * all files from all sub-arrays regardless how deeply nested they are.
  49. */
  50. public static function getInstancesByName($name)
  51. {
  52. $files = self::loadFiles();
  53. if (isset($files[$name])) {
  54. return [$files[$name]];
  55. }
  56. $results = [];
  57. foreach ($files as $key => $file) {
  58. if (strpos($key, "{$name}[") === 0) {
  59. $results[] = $file;
  60. }
  61. }
  62. return $results;
  63. }
复制代码

loadFiles()方法,把$_FILES中的键值作为参数传递到loadFilesRecursive($key, $names, $tempNames, $types, $sizes, $errors) 中

  1. /**
  2. * Creates UploadedFile instances from $_FILE.
  3. * @return array the UploadedFile instances
  4. */
  5. private static function loadFiles()
  6. {
  7. if (self::$_files === null) {
  8. self::$_files = [];
  9. if (isset($_FILES) && is_array($_FILES)) {
  10. foreach ($_FILES as $class => $info) {
  11. self::loadFilesRecursive($class, $info['name'], $info['tmp_name'], $info['type'], $info['size'], $info['error']);
  12. }
  13. }
  14. }
  15. return self::$_files;
  16. }
复制代码

loadFilesRecursive方法,通过递归把$_FILES中的内容保存到 self::$_files 中

  1. /**
  2. * Creates UploadedFile instances from $_FILE recursively.
  3. * @param string $key key for identifying uploaded file: class name and sub-array indexes
  4. * @param mixed $names file names provided by PHP
  5. * @param mixed $tempNames temporary file names provided by PHP
  6. * @param mixed $types file types provided by PHP
  7. * @param mixed $sizes file sizes provided by PHP
  8. * @param mixed $errors uploading issues provided by PHP
  9. */
  10. private static function loadFilesRecursive($key, $names, $tempNames, $types, $sizes, $errors)
  11. {
  12. if (is_array($names)) {
  13. foreach ($names as $i => $name) {
  14. self::loadFilesRecursive($key . '[' . $i . ']', $name, $tempNames[$i], $types[$i], $sizes[$i], $errors[$i]);
  15. }
  16. } elseif ($errors !== UPLOAD_ERR_NO_FILE) {
  17. self::$_files[$key] = new static([
  18. 'name' => $names,
  19. 'tempName' => $tempNames,
  20. 'type' => $types,
  21. 'size' => $sizes,
  22. 'error' => $errors,
  23. ]);
  24. }
  25. }
复制代码

实例:

html

  1. <form class="form-horizontal form-margin50" action="<?= \yii\helpers\Url::toRoute('upload-face') ?>"
  2. method="post" enctype="multipart/form-data" id="form1">
  3. <input type="hidden" name="_csrf" value="<?= Yii::$app->request->getCsrfToken() ?>">
  4. <input type="file" name="head_pic" id="doc" style="display: none" onchange="setImagePreview()"/>
  5. </form>
复制代码

php代码,打印的

  1. public static function uploadImage($userId = '', $tem = '')
  2. {
  3. $returnPath = '';
  4. $path = 'uploads/headpic/' . $userId;
  5. if (!file_exists($path)) {
  6. mkdir($path, 0777);
  7. chmod($path, 0777);
  8. }
  9. $patch = $path . '/' . date("YmdHis") . '_';
  10. $tmp = UploadedFile::getInstanceByName('head_pic');
  11. if ($tmp) {
  12. $patch = $path . '/' . date("YmdHis") . '_';
  13. $tmp->saveAs($patch . '1.jpg');
  14. $returnPath .= $patch;
  15. }
  16. return $returnPath;
  17. }
复制代码

打印dump($tmp,$_FILES,$tmp->getExtension());

对应的 UploadedFile

  1. class UploadedFile extends Object
  2. {
  3. /**
  4. * @var string the original name of the file being uploaded
  5. */
  6. // "Chrysanthemum.jpg"
  7. public $name;
  8. /**
  9. * @var string the path of the uploaded file on the server.
  10. * Note, this is a temporary file which will be automatically deleted by PHP
  11. * after the current request is processed.
  12. */
  13. // "C:\Windows\Temp\php8CEF.tmp"
  14. public $tempName;
  15. /**
  16. * @var string the MIME-type of the uploaded file (such as "image/gif").
  17. * Since this MIME type is not checked on the server-side, do not take this value for granted.
  18. * Instead, use [[\yii\helpers\FileHelper::getMimeType()]] to determine the exact MIME type.
  19. */
  20. // "image/jpeg"
  21. public $type;
  22. /**
  23. * @var integer the actual size of the uploaded file in bytes
  24. */
  25. // 879394
  26. public $size;
  27. /**
  28. * @var integer an error code describing the status of this file uploading.
  29. * @see http://www.php.net/manual/en/features.file-upload.errors.php
  30. */
  31. // 0
  32. public $error;
  33. private static $_files;
  34. /**
  35. * String output.
  36. * This is PHP magic method that returns string representation of an object.
  37. * The implementation here returns the uploaded file's name.
  38. * @return string the string representation of the object
  39. */
  40. public function __toString()
  41. {
  42. return $this->name;
  43. }
  44. /**
  45. * Returns an uploaded file for the given model attribute.
  46. * The file should be uploaded using [[\yii\widgets\ActiveField::fileInput()]].
  47. * @param \yii\base\Model $model the data model
  48. * @param string $attribute the attribute name. The attribute name may contain array indexes.
  49. * For example, '[1]file' for tabular file uploading; and 'file[1]' for an element in a file array.
  50. * @return UploadedFile the instance of the uploaded file.
  51. * Null is returned if no file is uploaded for the specified model attribute.
  52. * @see getInstanceByName()
  53. */
  54. public static function getInstance($model, $attribute)
  55. {
  56. $name = Html::getInputName($model, $attribute);
  57. return static::getInstanceByName($name);
  58. }
  59. /**
  60. * Returns all uploaded files for the given model attribute.
  61. * @param \yii\base\Model $model the data model
  62. * @param string $attribute the attribute name. The attribute name may contain array indexes
  63. * for tabular file uploading, e.g. '[1]file'.
  64. * @return UploadedFile[] array of UploadedFile objects.
  65. * Empty array is returned if no available file was found for the given attribute.
  66. */
  67. public static function getInstances($model, $attribute)
  68. {
  69. $name = Html::getInputName($model, $attribute);
  70. return static::getInstancesByName($name);
  71. }
  72. /**
  73. * Returns an uploaded file according to the given file input name.
  74. * The name can be a plain string or a string like an array element (e.g. 'Post[imageFile]', or 'Post[0][imageFile]').
  75. * @param string $name the name of the file input field.
  76. * @return null|UploadedFile the instance of the uploaded file.
  77. * Null is returned if no file is uploaded for the specified name.
  78. */
  79. public static function getInstanceByName($name)
  80. {
  81. $files = self::loadFiles();
  82. return isset($files[$name]) ? new static($files[$name]) : null;
  83. }
  84. /**
  85. * Returns an array of uploaded files corresponding to the specified file input name.
  86. * This is mainly used when multiple files were uploaded and saved as 'files[0]', 'files[1]',
  87. * 'files[n]'..., and you can retrieve them all by passing 'files' as the name.
  88. * @param string $name the name of the array of files
  89. * @return UploadedFile[] the array of UploadedFile objects. Empty array is returned
  90. * if no adequate upload was found. Please note that this array will contain
  91. * all files from all sub-arrays regardless how deeply nested they are.
  92. */
  93. public static function getInstancesByName($name)
  94. {
  95. $files = self::loadFiles();
  96. if (isset($files[$name])) {
  97. return [new static($files[$name])];
  98. }
  99. $results = [];
  100. foreach ($files as $key => $file) {
  101. if (strpos($key, "{$name}[") === 0) {
  102. $results[] = new static($file);
  103. }
  104. }
  105. return $results;
  106. }
  107. /**
  108. * Cleans up the loaded UploadedFile instances.
  109. * This method is mainly used by test scripts to set up a fixture.
  110. */
  111. //清空self::$_files
  112. public static function reset()
  113. {
  114. self::$_files = null;
  115. }
  116. /**
  117. * Saves the uploaded file.
  118. * Note that this method uses php's move_uploaded_file() method. If the target file `$file`
  119. * already exists, it will be overwritten.
  120. * @param string $file the file path used to save the uploaded file
  121. * @param boolean $deleteTempFile whether to delete the temporary file after saving.
  122. * If true, you will not be able to save the uploaded file again in the current request.
  123. * @return boolean true whether the file is saved successfully
  124. * @see error
  125. */
  126. //通过php的move_uploaded_file() 方法保存临时文件为目标文件
  127. public function saveAs($file, $deleteTempFile = true)
  128. {
  129. //$this->error == UPLOAD_ERR_OK UPLOAD_ERR_OK 其值为 0,没有错误发生,文件上传成功。
  130. if ($this->error == UPLOAD_ERR_OK) {
  131. if ($deleteTempFile) {
  132. //将上传的文件移动到新位置
  133. return move_uploaded_file($this->tempName, $file);
  134. } elseif (is_uploaded_file($this->tempName)) {//判断文件是否是通过 HTTP POST 上传的
  135. return copy($this->tempName, $file);//copy — 拷贝文件
  136. }
  137. }
  138. return false;
  139. }
  140. /**
  141. * @return string original file base name
  142. */
  143. //获取上传文件原始名称 "name" => "Chrysanthemum.jpg" "Chrysanthemum"
  144. public function getBaseName()
  145. {
  146. // https://github.com/yiisoft/yii2/issues/11012
  147. $pathInfo = pathinfo('_' . $this->name, PATHINFO_FILENAME);
  148. return mb_substr($pathInfo, 1, mb_strlen($pathInfo, '8bit'), '8bit');
  149. }
  150. /**
  151. * @return string file extension
  152. */
  153. //获取上传文件扩展名称 "name" => "Chrysanthemum.jpg" "jpg"
  154. public function getExtension()
  155. {
  156. return strtolower(pathinfo($this->name, PATHINFO_EXTENSION));
  157. }
  158. /**
  159. * @return boolean whether there is an error with the uploaded file.
  160. * Check [[error]] for detailed error code information.
  161. */
  162. //上传文件是否出现错误
  163. public function getHasError()
  164. {
  165. return $this->error != UPLOAD_ERR_OK;
  166. }
  167. /**
  168. * Creates UploadedFile instances from $_FILE.
  169. * @return array the UploadedFile instances
  170. */
  171. private static function loadFiles()
  172. {
  173. if (self::$_files === null) {
  174. self::$_files = [];
  175. if (isset($_FILES) && is_array($_FILES)) {
  176. foreach ($_FILES as $class => $info) {
  177. self::loadFilesRecursive($class, $info['name'], $info['tmp_name'], $info['type'], $info['size'], $info['error']);
  178. }
  179. }
  180. }
  181. return self::$_files;
  182. }
  183. /**
  184. * Creates UploadedFile instances from $_FILE recursively.
  185. * @param string $key key for identifying uploaded file: class name and sub-array indexes
  186. * @param mixed $names file names provided by PHP
  187. * @param mixed $tempNames temporary file names provided by PHP
  188. * @param mixed $types file types provided by PHP
  189. * @param mixed $sizes file sizes provided by PHP
  190. * @param mixed $errors uploading issues provided by PHP
  191. */
  192. private static function loadFilesRecursive($key, $names, $tempNames, $types, $sizes, $errors)
  193. {
  194. if (is_array($names)) {
  195. foreach ($names as $i => $name) {
  196. self::loadFilesRecursive($key . '[' . $i . ']', $name, $tempNames[$i], $types[$i], $sizes[$i], $errors[$i]);
  197. }
  198. } elseif ((int)$errors !== UPLOAD_ERR_NO_FILE) {
  199. self::$_files[$key] = [
  200. 'name' => $names,
  201. 'tempName' => $tempNames,
  202. 'type' => $types,
  203. 'size' => $sizes,
  204. 'error' => $errors,
  205. ];
  206. }
  207. }
  208. }
复制代码

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持程序员之家。



回复

使用道具 举报