UploaderService.php 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486
  1. <?php
  2. namespace App\Services;
  3. use Imagine\Gd\Imagine;
  4. use Imagine\Image\Box;
  5. use Imagine\Image\Point;
  6. class UploaderService
  7. {
  8. private $config; //配置信息
  9. private $fileField; //文件域名
  10. private $file; //文件上传对象
  11. private $base64; //文件上传对象
  12. private $oriName; //原始文件名
  13. private $fileName; //新文件名
  14. private $fullName; //完整文件名,即从当前配置目录开始的URL
  15. private $filePath; //完整文件名,即从当前配置目录开始的URL
  16. private $fileSize; //文件大小
  17. private $fileType; //文件类型
  18. public $thumbs = [];
  19. private $stateInfo; //上传状态信息,
  20. public $stateMap = [
  21. "SUCCESS",
  22. "文件大小超出 upload_max_filesize 限制",
  23. "文件大小超出 MAX_FILE_SIZE 限制",
  24. "文件未被完整上传",
  25. "没有文件被上传",
  26. "上传文件为空",
  27. "ERROR_TMP_FILE" => "临时文件错误",
  28. "ERROR_TMP_FILE_NOT_FOUND" => "找不到临时文件",
  29. "ERROR_SIZE_EXCEED" => "文件大小超出网站限制",
  30. "ERROR_TYPE_NOT_ALLOWED" => "文件类型不允许",
  31. "ERROR_CREATE_DIR" => "目录创建失败",
  32. "ERROR_DIR_NOT_WRITEABLE" => "目录没有写权限",
  33. "ERROR_FILE_MOVE" => "文件保存时出错",
  34. "ERROR_FILE_NOT_FOUND" => "找不到上传文件",
  35. "ERROR_WRITE_CONTENT" => "写入文件内容错误",
  36. "ERROR_UNKNOWN" => "未知错误",
  37. "ERROR_DEAD_LINK" => "链接不可用",
  38. "ERROR_HTTP_LINK" => "链接不是http链接",
  39. "ERROR_HTTP_CONTENTTYPE" => "链接contentType不正确",
  40. "INVALID_URL" => "非法 URL",
  41. "INVALID_IP" => "非法 IP"
  42. ];
  43. public function __construct($fileField, $config, $type = "upload")
  44. {
  45. $this->fileField = $fileField;
  46. $this->config = $config;
  47. $this->type = $type;
  48. if ($type == "remote") {
  49. return $this->saveRemote();
  50. } else if ($type == "base64") {
  51. return $this->upBase64();
  52. } else if ($type == 'crop') {
  53. return $this->createThumb();
  54. } else {
  55. return $this->upFile();
  56. }
  57. }
  58. /**
  59. * 上传文件的主处理方法
  60. *
  61. * @return mixed
  62. */
  63. private function upFile()
  64. {
  65. $file = $this->file = $_FILES[$this->fileField];
  66. if (!$file) {
  67. $this->stateInfo = $this->getStateInfo('ERROR_FILE_NOT_FOUND');
  68. return false;
  69. }
  70. if ($this->file['error']) {
  71. $this->stateInfo = $this->getStateInfo($file['error']);
  72. return false;
  73. } else if (!file_exists($file['tmp_name'])) {
  74. $this->stateInfo = $this->getStateInfo("ERROR_TMP_FILE_NOT_FOUND");
  75. return false;
  76. } else if (!is_uploaded_file($file['tmp_name'])) {
  77. $this->stateInfo = $this->getStateInfo("ERROR_TMPFILE");
  78. return false;
  79. }
  80. $this->oriName = $file['name'];
  81. $this->fileSize = $file['size'];
  82. $this->fileType = $this->getFileExt();
  83. $this->fullName = $this->getFullName();
  84. $this->filePath = $this->getFilePath();
  85. $this->fileName = $this->getFileName();
  86. $dirname = dirname($this->filePath);
  87. //检查文件大小是否超出限制
  88. if (!$this->checkSize()) {
  89. $this->stateInfo = $this->getStateInfo("ERROR_SIZE_EXCEED");
  90. return false;
  91. }
  92. //检查是否不允许的文件格式
  93. if (!$this->checkType()) {
  94. $this->stateInfo = $this->getStateInfo("ERROR_TYPE_NOT_ALLOWED");
  95. return false;
  96. }
  97. //创建目录失败
  98. if (!file_exists($dirname) && !mkdir($dirname, 0777, true)) {
  99. $this->stateInfo = $this->getStateInfo("ERROR_CREATE_DIR");
  100. return false;
  101. } else if (!is_writeable($dirname)) {
  102. $this->stateInfo = $this->getStateInfo("ERROR_DIR_NOT_WRITEABLE");
  103. return false;
  104. }
  105. //移动文件
  106. if (!(move_uploaded_file($file["tmp_name"], $this->filePath) && file_exists($this->filePath))) { //移动失败
  107. $this->stateInfo = $this->getStateInfo("ERROR_FILE_MOVE");
  108. return false;
  109. } else { //移动成功
  110. return true;
  111. }
  112. }
  113. /**
  114. * [
  115. * [
  116. * type:0, //默认为0 0 自动缩放 1 按照固定数据缩放 按照给定的宽高缩放 2 按照看缩放 3 按照高缩放
  117. * width:200px;
  118. * height:200px;
  119. * ],
  120. * [
  121. * x=>0,
  122. * y=>0,
  123. * width:200px;
  124. * height:200px;
  125. * ]
  126. * ]
  127. */
  128. public function createThumb()
  129. {
  130. $path = [];
  131. if (!isset($this->config['filePath'])) {
  132. die('图片不存在!');
  133. }
  134. $imgArr = parse_url($this->config['filePath']);
  135. $imgUrl = $imgArr['path'];
  136. $this->filePath = public_path($imgArr['path']);
  137. if ($arr = $this->getThumbArr()) {
  138. foreach ($arr as $value) {
  139. $imagine = new Imagine();
  140. $image = $imagine->open($this->filePath);
  141. $imageSize = $image->getSize();
  142. $imageW = $imageSize->getWidth();
  143. $imageH = $imageSize->getHeight();
  144. $aspectRatio = $imageW / $imageH;
  145. $metadata = $image->metadata()->toArray();
  146. if (isset($value['x']) || isset($value['y'])) {
  147. $x = $value['x'] ?? 0;
  148. $y = $value['y'] ?? 0;
  149. $w = $value['width'];
  150. $h = $value['height'];
  151. $imgPath = $this->filePath . $x . $y . $w . $h . '.jpg';
  152. $path[] = [
  153. 'path' => $imgUrl . $x . $y . $w . $h . '.jpg',
  154. 'realPath' => $imgPath,
  155. 'metadata' => $metadata,
  156. ];
  157. //图片先设置比例大小,然后再裁剪,宽度和高度最大值不能超过500px
  158. if ($imageW >= $imageH) {
  159. if ($imageW > 500) {
  160. $imageW = 500;
  161. $imageH = $imageW / $aspectRatio;
  162. }
  163. } else {
  164. if ($imageH > 500) {
  165. $imageH = 500;
  166. $imageW = $imageH * $aspectRatio;
  167. }
  168. }
  169. $point = new Point($x, $y);
  170. $size = new Box($imageW, $imageH);
  171. $box = new Box($value['width'], $value['height']);
  172. $image->resize($size)->crop($point, $box)->save($imgPath);
  173. }
  174. }
  175. }
  176. $this->thumbs = $path;
  177. }
  178. private function getThumbArr()
  179. {
  180. return $this->config['thumb'] ?? [];
  181. }
  182. /**
  183. * 处理base64编码的图片上传
  184. *
  185. * @return mixed
  186. */
  187. private function upBase64()
  188. {
  189. $base64Data = $_POST[$this->fileField];
  190. //截取字符串
  191. $base64Data = preg_replace('/data:image\/png;base64,/is', '', $base64Data);
  192. $img = base64_decode($base64Data);
  193. $this->oriName = $this->config['oriName'];
  194. $this->fileSize = strlen($img);
  195. $this->fileType = $this->getFileExt();
  196. $this->fullName = $this->getFullName();
  197. $this->filePath = $this->getFilePath();
  198. $this->fileName = $this->getFileName();
  199. $dirname = dirname($this->filePath);
  200. //检查文件大小是否超出限制
  201. if (!$this->checkSize()) {
  202. $this->stateInfo = $this->getStateInfo("ERROR_SIZE_EXCEED");
  203. return false;
  204. }
  205. //创建目录失败
  206. if (!file_exists($dirname) && !mkdir($dirname, 0777, true)) {
  207. $this->stateInfo = $this->getStateInfo("ERROR_CREATE_DIR");
  208. return false;
  209. } else if (!is_writeable($dirname)) {
  210. $this->stateInfo = $this->getStateInfo("ERROR_DIR_NOT_WRITEABLE");
  211. return false;
  212. }
  213. //移动文件
  214. if (!(file_put_contents($this->filePath, $img) && file_exists($this->filePath))) { //移动失败
  215. $this->stateInfo = $this->getStateInfo("ERROR_WRITE_CONTENT");
  216. return false;
  217. } else { //移动成功
  218. return true;
  219. }
  220. }
  221. /**
  222. * 拉取远程图片
  223. *
  224. * @return mixed
  225. */
  226. private function saveRemote()
  227. {
  228. $imgUrl = htmlspecialchars($this->fileField);
  229. $imgUrl = str_replace("&amp;", "&", $imgUrl);
  230. //http开头验证
  231. if (strpos($imgUrl, "http") !== 0) {
  232. $this->stateInfo = $this->getStateInfo("ERROR_HTTP_LINK");
  233. return false;
  234. }
  235. preg_match('/(^https*:\/\/[^:\/]+)/', $imgUrl, $matches);
  236. $host_with_protocol = count($matches) > 1 ? $matches[1] : '';
  237. // 判断是否是合法 url
  238. if (!filter_var($host_with_protocol, FILTER_VALIDATE_URL)) {
  239. $this->stateInfo = $this->getStateInfo("INVALID_URL");
  240. return false;
  241. }
  242. preg_match('/^https*:\/\/(.+)/', $host_with_protocol, $matches);
  243. $host_without_protocol = count($matches) > 1 ? $matches[1] : '';
  244. // 此时提取出来的可能是 ip 也有可能是域名,先获取 ip
  245. $ip = gethostbyname($host_without_protocol);
  246. // 判断是否是私有 ip
  247. if (!filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE)) {
  248. $this->stateInfo = $this->getStateInfo("INVALID_IP");
  249. return false;
  250. }
  251. //获取请求头并检测死链
  252. $heads = get_headers($imgUrl, 1);
  253. if (!(stristr($heads[0], "200") && stristr($heads[0], "OK"))) {
  254. $this->stateInfo = $this->getStateInfo("ERROR_DEAD_LINK");
  255. return false;
  256. }
  257. //格式验证(扩展名验证和Content-Type验证)
  258. $fileType = strtolower(strrchr($imgUrl, '.'));
  259. if (!in_array($fileType, $this->config['allowFiles']) || !isset($heads['Content-Type']) || !stristr($heads['Content-Type'], "image")) {
  260. $this->stateInfo = $this->getStateInfo("ERROR_HTTP_CONTENTTYPE");
  261. return false;
  262. }
  263. //打开输出缓冲区并获取远程图片
  264. ob_start();
  265. $context = stream_context_create(
  266. array('http' => array(
  267. 'follow_location' => false // don't follow redirects
  268. ))
  269. );
  270. readfile($imgUrl, false, $context);
  271. $img = ob_get_contents();
  272. ob_end_clean();
  273. preg_match("/[\/]([^\/]*)[\.]?[^\.\/]*$/", $imgUrl, $m);
  274. $this->oriName = $m ? $m[1] : "";
  275. $this->fileSize = strlen($img);
  276. $this->fileType = $this->getFileExt();
  277. $this->fullName = $this->getFullName();
  278. $this->filePath = $this->getFilePath();
  279. $this->fileName = $this->getFileName();
  280. $dirname = dirname($this->filePath);
  281. //检查文件大小是否超出限制
  282. if (!$this->checkSize()) {
  283. $this->stateInfo = $this->getStateInfo("ERROR_SIZE_EXCEED");
  284. return false;
  285. }
  286. //创建目录失败
  287. if (!file_exists($dirname) && !mkdir($dirname, 0777, true)) {
  288. $this->stateInfo = $this->getStateInfo("ERROR_CREATE_DIR");
  289. return false;
  290. } else if (!is_writeable($dirname)) {
  291. $this->stateInfo = $this->getStateInfo("ERROR_DIR_NOT_WRITEABLE");
  292. return false;
  293. }
  294. //移动文件
  295. if (!(file_put_contents($this->filePath, $img) && file_exists($this->filePath))) { //移动失败
  296. $this->stateInfo = $this->getStateInfo("ERROR_WRITE_CONTENT");
  297. return false;
  298. } else { //移动成功
  299. return true;
  300. }
  301. }
  302. /**
  303. * 返回错误信息
  304. *
  305. * @return mixed
  306. */
  307. public function getErrorMsg()
  308. {
  309. return $this->stateInfo;
  310. }
  311. /**
  312. * 上传错误检查
  313. *
  314. * @param $errCode
  315. * @return string
  316. */
  317. private function getStateInfo($errCode)
  318. {
  319. return !$this->stateMap[$errCode] ? $this->stateMap["ERROR_UNKNOWN"] : $this->stateMap[$errCode];
  320. }
  321. /**
  322. * 获取文件扩展名
  323. *
  324. * @return string
  325. */
  326. public function getFileExt()
  327. {
  328. return strtolower(strrchr($this->oriName, '.'));
  329. }
  330. /**
  331. * 重命名文件
  332. *
  333. * @return string
  334. */
  335. private function getFullName()
  336. {
  337. //替换日期事件
  338. $savePath = $this->config["savePath"];
  339. //文件名称随机
  340. if (isset($this->config['fileName']) && !empty($this->config['fileName'])) {
  341. $randNum = $this->config['fileName'];
  342. } else {
  343. $randNum = md5(microtime() . rand(1, 10000) . rand(1, 10000));
  344. }
  345. $ext = $this->getFileExt();
  346. return rtrim($savePath, '/') . '/' . $randNum . $ext;
  347. }
  348. /**
  349. * 获取文件名
  350. *
  351. * @return string
  352. */
  353. private function getFileName()
  354. {
  355. return substr($this->filePath, strrpos($this->filePath, '/') + 1);
  356. }
  357. /**
  358. * 获取文件完整路径
  359. *
  360. * @return string
  361. */
  362. private function getFilePath()
  363. {
  364. $fullname = $this->fullName;
  365. $rootPath = $_SERVER['DOCUMENT_ROOT'];
  366. if (substr($fullname, 0, 1) != '/') {
  367. $fullname = '/' . $fullname;
  368. }
  369. return $rootPath . $fullname;
  370. }
  371. /**
  372. * 文件类型检测
  373. *
  374. * @return bool
  375. */
  376. private function checkType()
  377. {
  378. return in_array($this->getFileExt(), $this->config["allowFiles"]);
  379. }
  380. /**
  381. * 文件大小检测
  382. *
  383. * @return bool
  384. */
  385. private function checkSize()
  386. {
  387. return $this->fileSize <= ($this->config["maxSize"]);
  388. }
  389. /**
  390. * 获取原上传文件的名称
  391. */
  392. public function getClientOriginalName()
  393. {
  394. return $this->oriName;
  395. }
  396. /**
  397. * 获取原上传文件的大小byte
  398. *
  399. * @return mixed
  400. */
  401. public function getClientSize()
  402. {
  403. return $this->fileSize;
  404. }
  405. /**
  406. * 获取文件的全路径
  407. */
  408. public function getFullPath()
  409. {
  410. return $this->fullName;
  411. }
  412. /**
  413. * 获取当前上传成功文件的各项信息
  414. *
  415. * @return array
  416. */
  417. public function getFileInfo()
  418. {
  419. return array(
  420. "state" => $this->stateInfo,
  421. "url" => $this->fullName,
  422. "title" => $this->fileName,
  423. "original" => $this->oriName,
  424. "type" => $this->fileType,
  425. "size" => $this->fileSize
  426. );
  427. }
  428. }