Upload.php 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333
  1. <?php
  2. namespace app\common\library;
  3. use app\common\exception\UploadException;
  4. use app\common\model\Attachment;
  5. use fast\Random;
  6. use FilesystemIterator;
  7. use think\Config;
  8. use think\File;
  9. use think\Hook;
  10. /**
  11. * 文件上传类
  12. */
  13. class Upload
  14. {
  15. /**
  16. * 验证码有效时长
  17. * @var int
  18. */
  19. protected static $expire = 120;
  20. /**
  21. * 最大允许检测的次数
  22. * @var int
  23. */
  24. protected static $maxCheckNums = 10;
  25. protected $chunkDir = null;
  26. protected $config = [];
  27. protected $error = '';
  28. /**
  29. * @var \think\File
  30. */
  31. protected $file = null;
  32. protected $fileInfo = null;
  33. public function __construct($file = null)
  34. {
  35. $this->config = Config::get('upload');
  36. $this->chunkDir = RUNTIME_PATH . 'chunks';
  37. if ($file) {
  38. $this->setFile($file);
  39. }
  40. }
  41. public function setChunkDir($dir)
  42. {
  43. $this->chunkDir = $dir;
  44. }
  45. public function getFile()
  46. {
  47. return $this->file;
  48. }
  49. public function setFile($file)
  50. {
  51. if (empty($file)) {
  52. throw new UploadException(__('No file upload or server upload limit exceeded'));
  53. }
  54. $fileInfo = $file->getInfo();
  55. $suffix = strtolower(pathinfo($fileInfo['name'], PATHINFO_EXTENSION));
  56. $suffix = $suffix && preg_match("/^[a-zA-Z0-9]+$/", $suffix) ? $suffix : 'file';
  57. $fileInfo['suffix'] = $suffix;
  58. $fileInfo['imagewidth'] = 0;
  59. $fileInfo['imageheight'] = 0;
  60. $this->file = $file;
  61. $this->fileInfo = $fileInfo;
  62. }
  63. protected function checkExecutable()
  64. {
  65. //禁止上传PHP和HTML文件
  66. if (in_array($this->fileInfo['type'], ['text/x-php', 'text/html']) || in_array($this->fileInfo['suffix'], ['php', 'html', 'htm'])) {
  67. throw new UploadException(__('Uploaded file format is limited'));
  68. }
  69. return true;
  70. }
  71. protected function checkMimetype()
  72. {
  73. $mimetypeArr = explode(',', strtolower($this->config['mimetype']));
  74. $typeArr = explode('/', $this->fileInfo['type']);
  75. //验证文件后缀
  76. if ($this->config['mimetype'] === '*'
  77. || in_array($this->fileInfo['suffix'], $mimetypeArr) || in_array('.' . $this->fileInfo['suffix'], $mimetypeArr)
  78. || in_array($this->fileInfo['type'], $mimetypeArr) || in_array($typeArr[0] . "/*", $mimetypeArr)) {
  79. return true;
  80. }
  81. throw new UploadException(__('Uploaded file format is limited'));
  82. }
  83. protected function checkImage($force = false)
  84. {
  85. //验证是否为图片文件
  86. if (in_array($this->fileInfo['type'], ['image/gif', 'image/jpg', 'image/jpeg', 'image/bmp', 'image/png', 'image/webp']) || in_array($this->fileInfo['suffix'], ['gif', 'jpg', 'jpeg', 'bmp', 'png', 'webp'])) {
  87. $imgInfo = getimagesize($this->fileInfo['tmp_name']);
  88. if (!$imgInfo || !isset($imgInfo[0]) || !isset($imgInfo[1])) {
  89. throw new UploadException(__('Uploaded file is not a valid image'));
  90. }
  91. $this->fileInfo['imagewidth'] = isset($imgInfo[0]) ? $imgInfo[0] : 0;
  92. $this->fileInfo['imageheight'] = isset($imgInfo[1]) ? $imgInfo[1] : 0;
  93. return true;
  94. } else {
  95. return !$force;
  96. }
  97. }
  98. protected function checkSize()
  99. {
  100. preg_match('/([0-9\.]+)(\w+)/', $this->config['maxsize'], $matches);
  101. $size = $matches ? $matches[1] : $this->config['maxsize'];
  102. $type = $matches ? strtolower($matches[2]) : 'b';
  103. $typeDict = ['b' => 0, 'k' => 1, 'kb' => 1, 'm' => 2, 'mb' => 2, 'gb' => 3, 'g' => 3];
  104. $size = (int)($size * pow(1024, isset($typeDict[$type]) ? $typeDict[$type] : 0));
  105. if ($this->fileInfo['size'] > $size) {
  106. throw new UploadException(__('File is too big (%sMiB). Max filesize: %sMiB.',
  107. round($this->fileInfo['size'] / pow(1024, 2), 2),
  108. round($size / pow(1024, 2), 2)));
  109. }
  110. }
  111. public function getSuffix()
  112. {
  113. return $this->fileInfo['suffix'] ?: 'file';
  114. }
  115. public function getSavekey($savekey = null, $filename = null, $md5 = null)
  116. {
  117. if ($filename) {
  118. $suffix = strtolower(pathinfo($filename, PATHINFO_EXTENSION));
  119. $suffix = $suffix && preg_match("/^[a-zA-Z0-9]+$/", $suffix) ? $suffix : 'file';
  120. } else {
  121. $suffix = $this->fileInfo['suffix'];
  122. }
  123. $filename = $filename ? $filename : ($suffix ? substr($this->fileInfo['name'], 0, strripos($this->fileInfo['name'], '.')) : $this->fileInfo['name']);
  124. $md5 = $md5 ? $md5 : md5_file($this->fileInfo['tmp_name']);
  125. $replaceArr = [
  126. '{year}' => date("Y"),
  127. '{mon}' => date("m"),
  128. '{day}' => date("d"),
  129. '{hour}' => date("H"),
  130. '{min}' => date("i"),
  131. '{sec}' => date("s"),
  132. '{random}' => Random::alnum(16),
  133. '{random32}' => Random::alnum(32),
  134. '{filename}' => $filename,
  135. '{suffix}' => $suffix,
  136. '{.suffix}' => $suffix ? '.' . $suffix : '',
  137. '{filemd5}' => $md5,
  138. ];
  139. $savekey = $savekey ? $savekey : $this->config['savekey'];
  140. $savekey = str_replace(array_keys($replaceArr), array_values($replaceArr), $savekey);
  141. return $savekey;
  142. }
  143. /**
  144. * 清理分片文件
  145. * @param $chunkid
  146. */
  147. public function clean($chunkid)
  148. {
  149. $iterator = new \GlobIterator($this->chunkDir . DS . $chunkid . '-*', FilesystemIterator::KEY_AS_FILENAME);
  150. $array = iterator_to_array($iterator);
  151. var_dump($array);
  152. }
  153. /**
  154. * 合并分片文件
  155. * @param string $chunkid
  156. * @param int $chunkcount
  157. * @param string $filename
  158. * @return attachment|\think\Model
  159. * @throws UploadException
  160. */
  161. public function merge($chunkid, $chunkcount, $filename)
  162. {
  163. $filePath = $this->chunkDir . DS . $chunkid;
  164. $completed = true;
  165. //检查所有分片是否都存在
  166. for ($i = 0; $i < $chunkcount; $i++) {
  167. if (!file_exists("{$filePath}-{$i}.part")) {
  168. $completed = false;
  169. break;
  170. }
  171. }
  172. if (!$completed) {
  173. throw new UploadException(__('Chunk file info error'));
  174. }
  175. //如果所有文件分片都上传完毕,开始合并
  176. $uploadPath = $filePath;
  177. if (!$destFile = @fopen($uploadPath, "wb")) {
  178. throw new UploadException(__('Chunk file merge error'));
  179. }
  180. if (flock($destFile, LOCK_EX)) { // 进行排他型锁定
  181. for ($i = 0; $i < $chunkcount; $i++) {
  182. $partFile = "{$filePath}-{$i}.part";
  183. if (!$handle = @fopen($partFile, "rb")) {
  184. break;
  185. }
  186. while ($buff = fread($handle, filesize($partFile))) {
  187. fwrite($destFile, $buff);
  188. }
  189. @fclose($handle);
  190. @unlink($partFile); //删除分片
  191. }
  192. flock($destFile, LOCK_UN);
  193. }
  194. @fclose($destFile);
  195. $file = new File($uploadPath);
  196. $info = [
  197. 'name' => $filename,
  198. 'type' => $file->getMime(),
  199. 'tmp_name' => $uploadPath,
  200. 'error' => 0,
  201. 'size' => $file->getSize()
  202. ];
  203. $file->setUploadInfo($info);
  204. $file->isTest(true);
  205. //重新设置文件
  206. $this->setFile($file);
  207. //允许大文件
  208. $this->config['maxsize'] = "1024G";
  209. return $this->upload();
  210. }
  211. /**
  212. * 分片上传
  213. * @throws UploadException
  214. */
  215. public function chunk($chunkid, $chunkindex, $chunkcount, $chunkfilesize = null, $chunkfilename = null, $direct = false)
  216. {
  217. if ($this->fileInfo['type'] != 'application/octet-stream') {
  218. throw new UploadException(__('Uploaded file format is limited'));
  219. }
  220. $destDir = RUNTIME_PATH . 'chunks';
  221. $fileName = $chunkid . "-" . $chunkindex . '.part';
  222. $destFile = $destDir . DS . $fileName;
  223. if (!is_dir($destDir)) {
  224. @mkdir($destDir, 0755, true);
  225. }
  226. if (!move_uploaded_file($this->file->getPathname(), $destFile)) {
  227. throw new UploadException(__('Chunk file write error'));
  228. }
  229. $file = new File($destFile);
  230. $this->setFile($file);
  231. return $file;
  232. }
  233. /**
  234. * 普通上传
  235. * @return \app\common\model\attachment|\think\Model
  236. * @throws UploadException
  237. */
  238. public function upload($savekey = null)
  239. {
  240. if (empty($this->file)) {
  241. throw new UploadException(__('No file upload or server upload limit exceeded'));
  242. }
  243. $this->checkSize();
  244. $this->checkExecutable();
  245. $this->checkMimetype();
  246. $this->checkImage();
  247. $savekey = $savekey ? $savekey : $this->getSavekey();
  248. $savekey = '/' . ltrim($savekey, '/');
  249. $uploadDir = substr($savekey, 0, strripos($savekey, '/') + 1);
  250. $fileName = substr($savekey, strripos($savekey, '/') + 1);
  251. $destDir = ROOT_PATH . 'public' . $uploadDir;
  252. $sha1 = $this->file->hash();
  253. $file = $this->file->move($destDir, $fileName);
  254. if (!$file) {
  255. // 上传失败获取错误信息
  256. throw new UploadException($this->file->getError());
  257. }
  258. $this->file = $file;
  259. $params = array(
  260. 'admin_id' => (int)session('admin.id'),
  261. 'user_id' => (int)cookie('uid'),
  262. 'filename' => htmlspecialchars(strip_tags($this->fileInfo['name'])),
  263. 'filesize' => $this->fileInfo['size'],
  264. 'imagewidth' => $this->fileInfo['imagewidth'],
  265. 'imageheight' => $this->fileInfo['imageheight'],
  266. 'imagetype' => $this->fileInfo['suffix'],
  267. 'imageframes' => 0,
  268. 'mimetype' => $this->fileInfo['type'],
  269. 'url' => $uploadDir . $file->getSaveName(),
  270. 'uploadtime' => time(),
  271. 'storage' => 'local',
  272. 'sha1' => $sha1,
  273. 'extparam' => '',
  274. );
  275. $attachment = new Attachment();
  276. $attachment->data(array_filter($params));
  277. $attachment->save();
  278. \think\Hook::listen("upload_after", $attachment);
  279. return $attachment;
  280. }
  281. public function setError($msg)
  282. {
  283. $this->error = $msg;
  284. }
  285. public function getError()
  286. {
  287. return $this->error;
  288. }
  289. }