UploadedFile.php 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234
  1. <?php
  2. /**
  3. * @link http://www.yiiframework.com/
  4. * @copyright Copyright (c) 2008 Yii Software LLC
  5. * @license http://www.yiiframework.com/license/
  6. */
  7. namespace yii\web;
  8. use yii\base\Object;
  9. use yii\helpers\Html;
  10. /**
  11. * UploadedFile represents the information for an uploaded file.
  12. *
  13. * You can call [[getInstance()]] to retrieve the instance of an uploaded file,
  14. * and then use [[saveAs()]] to save it on the server.
  15. * You may also query other information about the file, including [[name]],
  16. * [[tempName]], [[type]], [[size]] and [[error]].
  17. *
  18. * @property boolean $hasError Whether there is an error with the uploaded file. Check [[error]] for detailed
  19. * error code information. This property is read-only.
  20. *
  21. * @author Qiang Xue <[email protected]>
  22. * @since 2.0
  23. */
  24. class UploadedFile extends Object
  25. {
  26. private static $_files;
  27. /**
  28. * @var string the original name of the file being uploaded
  29. */
  30. public $name;
  31. /**
  32. * @var string the path of the uploaded file on the server.
  33. * Note, this is a temporary file which will be automatically deleted by PHP
  34. * after the current request is processed.
  35. */
  36. public $tempName;
  37. /**
  38. * @var string the MIME-type of the uploaded file (such as "image/gif").
  39. * Since this MIME type is not checked on the server side, do not take this value for granted.
  40. * Instead, use [[FileHelper::getMimeType()]] to determine the exact MIME type.
  41. */
  42. public $type;
  43. /**
  44. * @var integer the actual size of the uploaded file in bytes
  45. */
  46. public $size;
  47. /**
  48. * @var integer an error code describing the status of this file uploading.
  49. * @see http://www.php.net/manual/en/features.file-upload.errors.php
  50. */
  51. public $error;
  52. /**
  53. * String output.
  54. * This is PHP magic method that returns string representation of an object.
  55. * The implementation here returns the uploaded file's name.
  56. * @return string the string representation of the object
  57. */
  58. public function __toString()
  59. {
  60. return $this->name;
  61. }
  62. /**
  63. * Returns an uploaded file for the given model attribute.
  64. * The file should be uploaded using [[ActiveForm::fileInput()]].
  65. * @param \yii\base\Model $model the data model
  66. * @param string $attribute the attribute name. The attribute name may contain array indexes.
  67. * For example, '[1]file' for tabular file uploading; and 'file[1]' for an element in a file array.
  68. * @return UploadedFile the instance of the uploaded file.
  69. * Null is returned if no file is uploaded for the specified model attribute.
  70. * @see getInstanceByName()
  71. */
  72. public static function getInstance($model, $attribute)
  73. {
  74. $name = Html::getInputName($model, $attribute);
  75. return static::getInstanceByName($name);
  76. }
  77. /**
  78. * Returns all uploaded files for the given model attribute.
  79. * @param \yii\base\Model $model the data model
  80. * @param string $attribute the attribute name. The attribute name may contain array indexes
  81. * for tabular file uploading, e.g. '[1]file'.
  82. * @return UploadedFile[] array of UploadedFile objects.
  83. * Empty array is returned if no available file was found for the given attribute.
  84. */
  85. public static function getInstances($model, $attribute)
  86. {
  87. $name = Html::getInputName($model, $attribute);
  88. return static::getInstancesByName($name);
  89. }
  90. /**
  91. * Returns an uploaded file according to the given file input name.
  92. * The name can be a plain string or a string like an array element (e.g. 'Post[imageFile]', or 'Post[0][imageFile]').
  93. * @param string $name the name of the file input field.
  94. * @return UploadedFile the instance of the uploaded file.
  95. * Null is returned if no file is uploaded for the specified name.
  96. */
  97. public static function getInstanceByName($name)
  98. {
  99. $files = static::loadFiles();
  100. return isset($files[$name]) ? $files[$name] : null;
  101. }
  102. /**
  103. * Returns an array of uploaded files corresponding to the specified file input name.
  104. * This is mainly used when multiple files were uploaded and saved as 'files[0]', 'files[1]',
  105. * 'files[n]'..., and you can retrieve them all by passing 'files' as the name.
  106. * @param string $name the name of the array of files
  107. * @return UploadedFile[] the array of CUploadedFile objects. Empty array is returned
  108. * if no adequate upload was found. Please note that this array will contain
  109. * all files from all sub-arrays regardless how deeply nested they are.
  110. */
  111. public static function getInstancesByName($name)
  112. {
  113. $files = static::loadFiles();
  114. if (isset($files[$name])) {
  115. return [$files[$name]];
  116. }
  117. $results = [];
  118. foreach ($files as $key => $file) {
  119. if (strpos($key, "{$name}[") === 0) {
  120. $results[] = self::$_files[$key];
  121. }
  122. }
  123. return $results;
  124. }
  125. /**
  126. * Cleans up the loaded UploadedFile instances.
  127. * This method is mainly used by test scripts to set up a fixture.
  128. */
  129. public static function reset()
  130. {
  131. self::$_files = null;
  132. }
  133. /**
  134. * Saves the uploaded file.
  135. * Note that this method uses php's move_uploaded_file() method. If the target file `$file`
  136. * already exists, it will be overwritten.
  137. * @param string $file the file path used to save the uploaded file
  138. * @param boolean $deleteTempFile whether to delete the temporary file after saving.
  139. * If true, you will not be able to save the uploaded file again in the current request.
  140. * @return boolean true whether the file is saved successfully
  141. * @see error
  142. */
  143. public function saveAs($file, $deleteTempFile = true)
  144. {
  145. if ($this->error == UPLOAD_ERR_OK) {
  146. if ($deleteTempFile) {
  147. return move_uploaded_file($this->tempName, $file);
  148. } elseif (is_uploaded_file($this->tempName)) {
  149. return copy($this->tempName, $file);
  150. }
  151. }
  152. return false;
  153. }
  154. /**
  155. * @return string original file base name
  156. */
  157. public function getBaseName()
  158. {
  159. return pathinfo($this->name, PATHINFO_FILENAME);
  160. }
  161. /**
  162. * @return string file extension
  163. */
  164. public function getExtension()
  165. {
  166. return strtolower(pathinfo($this->name, PATHINFO_EXTENSION));
  167. }
  168. /**
  169. * @return boolean whether there is an error with the uploaded file.
  170. * Check [[error]] for detailed error code information.
  171. */
  172. public function getHasError()
  173. {
  174. return $this->error != UPLOAD_ERR_OK;
  175. }
  176. /**
  177. * Creates UploadedFile instances from $_FILE.
  178. * @return array the UploadedFile instances
  179. */
  180. private static function loadFiles()
  181. {
  182. if (self::$_files === null) {
  183. self::$_files = [];
  184. if (isset($_FILES) && is_array($_FILES)) {
  185. foreach ($_FILES as $class => $info) {
  186. self::loadFilesRecursive($class, $info['name'], $info['tmp_name'], $info['type'], $info['size'], $info['error']);
  187. }
  188. }
  189. }
  190. return self::$_files;
  191. }
  192. /**
  193. * Creates UploadedFile instances from $_FILE recursively.
  194. * @param string $key key for identifying uploaded file: class name and sub-array indexes
  195. * @param mixed $names file names provided by PHP
  196. * @param mixed $tempNames temporary file names provided by PHP
  197. * @param mixed $types file types provided by PHP
  198. * @param mixed $sizes file sizes provided by PHP
  199. * @param mixed $errors uploading issues provided by PHP
  200. */
  201. private static function loadFilesRecursive($key, $names, $tempNames, $types, $sizes, $errors)
  202. {
  203. if (is_array($names)) {
  204. foreach ($names as $i => $name) {
  205. self::loadFilesRecursive($key . '[' . $i . ']', $name, $tempNames[$i], $types[$i], $sizes[$i], $errors[$i]);
  206. }
  207. } else {
  208. self::$_files[$key] = new static([
  209. 'name' => $names,
  210. 'tempName' => $tempNames,
  211. 'type' => $types,
  212. 'size' => $sizes,
  213. 'error' => $errors,
  214. ]);
  215. }
  216. }
  217. }