UploadService.php 15 KB

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