UploadService.php 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470
  1. <?php
  2. /**
  3. *
  4. * @author: xaboy<365615158@qq.com>
  5. * @day: 2017/10/24
  6. */
  7. namespace crmeb\services;
  8. use crmeb\services\storage\COS;
  9. use crmeb\services\storage\OSS;
  10. use crmeb\services\storage\Qiniu;
  11. use crmeb\traits\LogicTrait;
  12. use think\exception\ValidateException;
  13. use think\facade\Filesystem;
  14. use Guzzle\Http\EntityBody;
  15. use think\File;
  16. /**
  17. * Class UploadService
  18. * @package crmeb\services
  19. * @method $this setReturnErr(bool $returnErr) 设置发生错误时是否返回错误信息
  20. * @method $this setAutoValidate(bool $autoValidate) 设置是否校验上传文件
  21. * @method $this setUploadType(int $uploadType) 设置上传类型
  22. * @method $this setImageValidate(string $imageValidate) 设置上传图片大小等验证信息
  23. * @method $this setUploadPath(string $uploadPath) 设置文件上传路径
  24. */
  25. class UploadService
  26. {
  27. use LogicTrait;
  28. /**
  29. * 文件校验
  30. * @var bool
  31. */
  32. protected $autoValidate = false;
  33. /**
  34. * 上传路径
  35. * @var string
  36. */
  37. protected $uploadPath;
  38. /**
  39. * 上传类型
  40. * @var int
  41. */
  42. protected $uploadType;
  43. /**
  44. * 发生错误时是否返回错误信息
  45. * @var bool
  46. */
  47. protected $returnErr = false;
  48. /**
  49. * 上传文件返回数组初始值
  50. * @var array
  51. */
  52. protected $uploadInfo = [
  53. 'name' => '',
  54. 'size' => 0,
  55. 'type' => 'image/jpeg',
  56. 'dir' => '',
  57. 'thumb_path' => '',
  58. 'image_type' => '',
  59. 'time' => 0,
  60. ];
  61. /**
  62. * 上传信息
  63. * @var object
  64. */
  65. private static $uploadStatus;
  66. /**
  67. * 上传图片的大小 2MB 单位字节
  68. * @var string
  69. */
  70. protected $imageValidate = null;
  71. /**
  72. * 上传规则
  73. * @var array
  74. */
  75. protected $imageValidateArray = [
  76. 'filesize' => 2097152,
  77. 'fileExt' => ['jpg', 'jpeg', 'png', 'gif', 'pem', 'mp3', 'wma', 'wav', 'amr', 'mp4'],
  78. 'fileMime' => ['image/jpeg', 'image/gif', 'image/png', 'text/plain', 'audio/mpeg'],
  79. ];
  80. protected $propsRule = [
  81. 'returnErr' => false,
  82. 'autoValidate' => false,
  83. 'uploadPath' => null,
  84. 'uploadType' => null,
  85. ];
  86. protected function __construct()
  87. {
  88. $this->init();
  89. }
  90. /**
  91. * 初始化
  92. */
  93. protected function init()
  94. {
  95. self::$uploadStatus = new \StdClass();
  96. $this->extractValidate();
  97. }
  98. /**
  99. * 提取上传验证
  100. */
  101. protected function extractValidate()
  102. {
  103. $imageValidate = [];
  104. foreach ($this->imageValidateArray as $key => $value) {
  105. $imageValidate[] = $key . ':' . (is_array($value) ? implode(',', $value) : $value);
  106. }
  107. $this->imageValidate = implode('|', $imageValidate);
  108. unset($imageValidate);
  109. }
  110. /**
  111. * 设置上传验证
  112. * @param array $imageValidateArray
  113. * @return $this
  114. */
  115. public function setImageValidateArray(array $imageValidateArray)
  116. {
  117. if (isset($imageValidateArray['filesize']) && !is_int($imageValidateArray['filesize'])) {
  118. $imageValidateArray['filesize'] = 2097152;
  119. }
  120. $this->imageValidateArray = array_merge($this->imageValidateArray, $imageValidateArray);
  121. $this->extractValidate();
  122. return $this;
  123. }
  124. /**
  125. * 返回失败信息
  126. * @param $error
  127. * @return mixed
  128. */
  129. protected static function setError($error)
  130. {
  131. self::$uploadStatus->status = false;
  132. self::$uploadStatus->error = $error;
  133. return self::$uploadStatus;
  134. }
  135. /**
  136. * 返回成功信息
  137. * @param $path
  138. * @return mixed
  139. */
  140. protected static function successful($path)
  141. {
  142. self::$uploadStatus->status = true;
  143. self::$uploadStatus->filePath = '/uploads/' . $path;
  144. return self::$uploadStatus;
  145. }
  146. /**
  147. * 检查上传目录不存在则生成
  148. * @param $dir
  149. * @return bool
  150. */
  151. protected static function validDir($dir)
  152. {
  153. return is_dir($dir) == true || mkdir($dir, 0777, true) == true;
  154. }
  155. /**
  156. * 生成上传文件目录
  157. * @param $path
  158. * @param null $root
  159. * @return string
  160. */
  161. protected static function uploadDir($path, $root = null)
  162. {
  163. if ($root === null) $root = app()->getRootPath() . 'public' . DS;
  164. return $root . 'uploads' . DS . $path;
  165. }
  166. /**
  167. * 单图上传
  168. * @param string $fileName 上传文件名
  169. * @return mixed
  170. */
  171. public function image($fileName)
  172. {
  173. $info = [];
  174. try {
  175. $uploadType = $this->uploadType ?: sys_config('upload_type');
  176. //TODO 没有选择默认使用本地上传
  177. if (!$uploadType)
  178. $uploadType = 1;
  179. if (!is_int($uploadType))
  180. $uploadType = (int)$uploadType;
  181. switch ($uploadType) {
  182. case 1 :
  183. $info = $this->uploadLocaFile($fileName);
  184. if (is_string($info)) return $info;
  185. break;
  186. case 2 :
  187. $keys = Qiniu::uploadImage($fileName);
  188. if (is_array($keys)) {
  189. foreach ($keys as $key => &$item) {
  190. if (is_array($item)) {
  191. $info = Qiniu::imageUrl($item['key']);
  192. $info = $this->setUploadInfo($info['dir'], 2, $item['key'], UtilService::setHttpType($info['thumb_path']));
  193. }
  194. }
  195. } else return $keys;
  196. break;
  197. case 3 :
  198. $serverImageInfo = OSS::uploadImage($fileName);
  199. if (!is_array($serverImageInfo)) return $serverImageInfo;
  200. $info = $this->setUploadInfo(UtilService::setHttpType($serverImageInfo['info']['url']), 3, substr(strrchr($serverImageInfo['info']['url'], '/'), 1));
  201. break;
  202. case 4 :
  203. list($imageUrl, $serverImageInfo) = COS::uploadImage($fileName);
  204. if (!is_array($serverImageInfo) && !is_object($serverImageInfo)) return $serverImageInfo;
  205. $info = $this->setUploadInfo($imageUrl, 4, substr(strrchr($imageUrl, '/'), 1));
  206. break;
  207. default:
  208. $info = $this->uploadLocaFile($fileName);
  209. if (is_string($info)) return $info;
  210. break;
  211. }
  212. } catch (\Exception $e) {
  213. return $e->getMessage();
  214. }
  215. return $info;
  216. }
  217. /**
  218. * 获取图片类型和大小
  219. * @param string $url 图片地址
  220. * @param int $type 类型
  221. * @param bool $isData 是否真实获取图片信息
  222. * @return array
  223. */
  224. public static function getImageHeaders(string $url, $type = 1, $isData = true)
  225. {
  226. stream_context_set_default([
  227. 'ssl' => [
  228. 'verify_peer' => false,
  229. 'verify_peer_name' => false,
  230. ],
  231. ]);
  232. $header['Content-Length'] = 0;
  233. $header['Content-Type'] = 'image/jpeg';
  234. if (!$isData) return $header;
  235. try {
  236. $header = get_headers(str_replace('\\', '/', UtilService::setHttpType($url, $type)), true);
  237. if (!isset($header['Content-Length'])) $header['Content-Length'] = 0;
  238. if (!isset($header['Content-Type'])) $header['Content-Type'] = 'image/jpeg';
  239. } catch (\Exception $e) {
  240. }
  241. return $header;
  242. }
  243. /**
  244. * 本地文件上传
  245. * @param $fileName
  246. * @return array|string
  247. */
  248. public function uploadLocaFile($fileName)
  249. {
  250. $file = request()->file($fileName);
  251. if (!$file) return '上传文件不存在!';
  252. if ($this->autoValidate) {
  253. try {
  254. validate([$fileName => $this->imageValidate])->check([$fileName => $file]);
  255. } catch (ValidateException $e) {
  256. return $e->getMessage();
  257. }
  258. }
  259. $fileName = Filesystem::putFile($this->uploadPath, $file);
  260. if (!$fileName) return '图片上传失败!';
  261. $filePath = Filesystem::path($fileName);
  262. $fileInfo = new File($filePath);
  263. $url = '/uploads/' . $fileName;
  264. $this->uploadPath = '';
  265. $this->autoValidate = false;
  266. return $this->setUploadInfo($url, 1, $fileInfo->getFilename(), self::thumb('.' . $url), [
  267. 'Content-Length' => $fileInfo->getSize(),
  268. 'Content-Type' => $fileInfo->getMime()
  269. ]);
  270. }
  271. /**
  272. * 本地文件流上传
  273. * @param $key
  274. * @param $content
  275. * @param string $root
  276. * @return array|string
  277. */
  278. public function uploadLocalStream($key, $content, $root = '')
  279. {
  280. $siteUrl = sys_config('site_url') . '/';
  281. $path = self::uploadDir($this->uploadPath, $root);
  282. $path = str_replace('\\', DS, $path);
  283. $path = str_replace('/', DS, $path);
  284. $dir = $path;
  285. if (!self::validDir($dir)) return '生成上传目录失败,请检查权限!';
  286. $name = $path . DS . $key;
  287. file_put_contents($name, $content);
  288. $path = str_replace('\\', '/', $path);
  289. $headerArray = self::getImageHeaders($siteUrl . $path . '/' . $key);
  290. $url = '/' . $path . '/' . $key;
  291. return $this->setUploadInfo($url, 1, $key, $url, $headerArray);
  292. }
  293. /**
  294. * TODO 文件流上传
  295. * @param $key
  296. * @param $content
  297. * @param null $root
  298. * @return array|string
  299. * @throws \Exception
  300. */
  301. public function imageStream($key, $content, $root = '')
  302. {
  303. $uploadType = sys_config('upload_type');
  304. //TODO 没有选择默认使用本地上传
  305. if (!$uploadType) $uploadType = 1;
  306. $info = [];
  307. switch ($uploadType) {
  308. case 1 :
  309. $info = $this->uploadLocalStream($key, $content, $root);
  310. if (is_string($info)) return $info;
  311. break;
  312. case 2 :
  313. $keys = Qiniu::uploadImageStream($key, $content);
  314. if (is_array($keys)) {
  315. foreach ($keys as $key => &$item) {
  316. if (is_array($item)) {
  317. $info = Qiniu::imageUrl($item['key']);
  318. $info['dir'] = UtilService::setHttpType($info['dir']);
  319. $info = $this->setUploadInfo($info['dir'], 2, $item['key'], $info['thumb_path']);
  320. }
  321. }
  322. if (!count($info)) return '七牛云文件上传失败';
  323. } else return $keys;
  324. break;
  325. case 3 :
  326. $content = COS::resourceStream($content);
  327. $serverImageInfo = OSS::uploadImageStream($key, $content);
  328. if (!is_array($serverImageInfo)) return $serverImageInfo;
  329. $info = $this->setUploadInfo(UtilService::setHttpType($serverImageInfo['info']['url']), 3, substr(strrchr($serverImageInfo['info']['url'], '/'), 1));
  330. break;
  331. case 4 :
  332. list($imageUrl, $serverImageInfo) = COS::uploadImageStream($key, $content);
  333. if (!is_array($serverImageInfo) && !is_object($serverImageInfo)) return $serverImageInfo;
  334. $info = $this->setUploadInfo($imageUrl, 4, substr(strrchr($imageUrl, '/'), 1));
  335. break;
  336. default:
  337. $info = $this->uploadLocalStream($key, $content, $root);
  338. if (is_string($info)) return $info;
  339. break;
  340. }
  341. $this->uploadPath = '';
  342. $this->autoValidate = true;
  343. return $info;
  344. }
  345. /**
  346. * 设置返回的数据信息
  347. * @param string $url
  348. * @param int $imageType
  349. * @param string $name
  350. * @param string $thumbPath
  351. * @return array
  352. */
  353. protected function setUploadInfo(string $url, int $imageType, string $name = '', string $thumbPath = '', array $headerArray = [])
  354. {
  355. $headerArray = count($headerArray) ? $headerArray : self::getImageHeaders($url);
  356. if (is_array($headerArray['Content-Type']) && count($headerArray['Content-Length']) == 2) {
  357. $headerArray['Content-Length'] = $headerArray['Content-Length'][1];
  358. }
  359. if (is_array($headerArray['Content-Type']) && count($headerArray['Content-Type']) == 2) {
  360. $headerArray['Content-Type'] = $headerArray['Content-Type'][1];
  361. }
  362. $info = [
  363. 'name' => str_replace('\\', '/', $name ?: $url),
  364. 'dir' => str_replace('\\', '/', $url),
  365. 'size' => $headerArray['Content-Length'],
  366. 'type' => $headerArray['Content-Type'],
  367. 'time' => time(),
  368. 'thumb_path' => str_replace('\\', '/', $thumbPath ?: $url),
  369. 'image_type' => $imageType,
  370. ];
  371. $uploadInfo = array_merge($this->uploadInfo, $info);
  372. return $uploadInfo;
  373. }
  374. /**
  375. * 文件上传
  376. * @param string $fileName 上传文件名
  377. * @return mixed
  378. */
  379. public function file($fileName)
  380. {
  381. $file = request()->file($fileName);
  382. if (!$file) return self::setError('上传文件不存在!');
  383. if (strtolower($file->getOriginalExtension()) === 'php' || !$file->getOriginalExtension())
  384. return self::setError('上传文件非法!');
  385. if ($this->autoValidate) {
  386. try {
  387. validate([$fileName => $this->imageValidate])->check([$fileName => $file]);
  388. } catch (ValidateException $e) {
  389. return self::setError($e->getMessage());
  390. }
  391. };
  392. $fileName = Filesystem::putFile($this->uploadPath, $file);
  393. if (!$fileName) return self::setError('图片上传失败!');
  394. return self::successful(str_replace('\\', '/', $fileName));
  395. }
  396. /**
  397. * 打开图片
  398. * @param $filePath
  399. * @return \think\Image
  400. */
  401. public function openImage($filePath)
  402. {
  403. return \think\Image::open($filePath);
  404. }
  405. /**
  406. * 图片压缩
  407. *
  408. * @param string $filePath 文件路径
  409. * @param int $ratio 缩放比例 1-9
  410. * @param string $pre 前缀
  411. * @return string 压缩图片路径
  412. */
  413. public function thumb($filePath, $ratio = 5, $pre = 's_')
  414. {
  415. try {
  416. $img = $this->openImage($filePath);
  417. } catch (\Throwable $e) {
  418. $dir = dirname($filePath);
  419. $fileName = basename($filePath);
  420. return $dir . DS . $fileName;
  421. }
  422. $width = $img->width() * $ratio / 10;
  423. $height = $img->height() * $ratio / 10;
  424. $dir = dirname($filePath);
  425. $fileName = basename($filePath);
  426. $savePath = $dir . DS . $pre . $fileName;
  427. $img->thumb($width, $height)->save($savePath);
  428. if (substr($savePath, 0, 2) == './') return substr($savePath, 1, strlen($savePath));
  429. return DS . $savePath;
  430. }
  431. /**
  432. * TODO 转为文件流
  433. * @param $resource
  434. * @return EntityBody
  435. */
  436. public static function resourceStream($resource)
  437. {
  438. return EntityBody::factory($resource)->__toString();
  439. }
  440. }