File.php 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363
  1. <?php
  2. namespace app\oss\controller;
  3. use app\common\service\HelperService;
  4. use app\oss\service\OssServiceV2;
  5. use Exception;
  6. use think\Config;
  7. use think\Controller;
  8. use think\Validate;
  9. class File extends Controller {
  10. private static $fileType = array(
  11. 'image' => 1,
  12. 'audio' => 2,
  13. 'video' => 3,
  14. 'text' => 4,
  15. 'file' => 5,
  16. 'pdf' => 6
  17. );
  18. public function _initialize() {
  19. parent::_initialize();
  20. }
  21. private function setConfig($bucket){
  22. switch($bucket){
  23. case 'viva-private':
  24. Config::set('OSS_ACCESS_KEY_ID','LTAI4G9Zz1yWLASYkBmXRFF6');
  25. Config::set('ACCESS_KEY_SECRET','pnMsp9wlTEo4lP0JQgVukMGURlcC7y');
  26. Config::set('OSS_ENDPOINT','oss-cn-hangzhou.aliyuncs.com');
  27. break;
  28. default:
  29. throw new \RuntimeException('无此bucket');
  30. }
  31. }
  32. public function newDiffParam($rule, $params) {
  33. $validate = new Validate($rule);
  34. if (!$validate->check($params)) {
  35. HelperService::returnJson(['code'=>400,'msg'=>$validate->getError()]);
  36. }
  37. }
  38. /**
  39. * 图片上传
  40. */
  41. public function upload() {
  42. header('Access-Control-Allow-Origin:*');
  43. header("Access-Control-Allow-Methods", "*");
  44. header("Access-Control-Allow-Headers", "Content-Type,XFILENAME,XFILECATEGORY,XFILESIZE");
  45. $params = $this->request->param();
  46. $rule = [
  47. 'fileName' => 'require',
  48. 'upType' => 'require',
  49. 'isRoot' => 'require',
  50. 'fileType' => 'require|number',
  51. 'bucket' => 'require',
  52. 'isPrivate' => 'boolean'
  53. ];
  54. if (isset($params['upType']) && $params['upType'] === 'base64') {
  55. $rule['content'] = 'require';
  56. }
  57. $this->newDiffParam($rule, $params);
  58. $fileName = (string)$params['fileName'];
  59. $upType = (string)$params['upType'];
  60. $isRoot = (string)$params['isRoot'];
  61. $fileType = (string)$params['fileType'];
  62. $isPrivate = isset($params['isPrivate']) ?$params['isPrivate']: true;
  63. $bucket = $params['bucket'];
  64. $this->setConfig($bucket);
  65. Config::set('ALIYUN_OSS_BUCKET', $bucket);
  66. $ossService = new OssServiceV2($bucket);
  67. $ext = !empty($fileName) ? (string)pathinfo($fileName, PATHINFO_EXTENSION) : '';
  68. list($fileName, $realContent) = $ossService->getFileNameAndRealContent($upType, $params, $fileName, $ext);
  69. //向阿里推送图片
  70. $type = (array)array_flip(self::$fileType);
  71. if(empty($type[$fileType])){
  72. HelperService::returnJson(['code'=>400,'msg'=>'文件类型不正确']);
  73. }
  74. $fileSavePath = $isRoot ? ltrim($fileName, '/') : $type[$fileType] . '/' . date('Ym') . '/' . $fileName;
  75. //重试3次
  76. $times = 3;
  77. $message = '';
  78. while ($times--) {
  79. try {
  80. if (true === $ossService->fileExist($fileSavePath)) {
  81. $path = (string)pathinfo($fileSavePath, PATHINFO_DIRNAME);
  82. $path = ($path === '.' || $path === '..') ? '' : $path;
  83. $fileName = pathinfo($fileSavePath, PATHINFO_BASENAME);
  84. $ext = pathinfo($fileSavePath, PATHINFO_EXTENSION);
  85. $fileName = substr($fileName, 0, strpos($fileName, '.' . $ext));
  86. $newFileName = $fileName . '_' . date('YmdHis') . mt_rand(10000, 99999) . '.' . $ext;
  87. $fileSavePath = ltrim($path . '/' . $newFileName, '/');
  88. }
  89. $result = $ossService->fileUpload($fileSavePath, $realContent);
  90. if ($isPrivate === true) {
  91. $ossService->putObjectAcl($result, 'private');
  92. }
  93. if ($result) {
  94. $aLiYunUrl = 'http://' . $bucket . '.' . Config::get('OSS_ENDPOINT') . '/' . trim($result, '/');
  95. HelperService::returnJson(['data'=>[
  96. 'url' => $result,
  97. 'bucket' => $bucket,
  98. 'aliyunUrl' => $aLiYunUrl,
  99. 'signUrl' => $ossService->getSignUrl([
  100. 'object' => $result,
  101. 'bucket' => $bucket
  102. ])
  103. ],'msg'=>'success','code'=>200]);
  104. } else {
  105. HelperService::returnJson(['data'=>['times' => $times, 'bucket' => $bucket], 'msg'=>'fail','code'=>400]);
  106. }
  107. } catch (Exception $ex) {
  108. $message = $ex->getMessage();
  109. continue;
  110. }
  111. }
  112. HelperService::returnJson(['data'=>['times' => $times, 'bucket' => $bucket], 'msg'=>'上传失败: ' . $message,'code'=>400]);
  113. }
  114. protected function input() {
  115. $contents = file_get_contents('php://input');
  116. $param = json_decode($contents, true);
  117. if (empty($param))
  118. return $this->output([], 'json error', '0004');
  119. return $param;
  120. }
  121. public function output($data=[],$msg='success',$code=200){
  122. HelperService::returnJson([
  123. 'data'=>$data,
  124. 'msg'=>$msg,
  125. 'code'=>$code
  126. ]);
  127. }
  128. /**
  129. * 下载文件
  130. */
  131. public function downFile() {
  132. $params = $this->input();
  133. $this->newDiffParam([
  134. 'filePath' => 'require',
  135. 'bucket' => 'require'
  136. ], $params);
  137. $this->setConfig($params['bucket']);
  138. Config::set('ALIYUN_OSS_BUCKET', (string)($params['bucket']));
  139. $res = (new OssServiceV2((string)($params['bucket'])))->downFile((string)($params['filePath']));
  140. die($res);
  141. }
  142. /**
  143. * 文件删除
  144. */
  145. public function fileDelete() {
  146. $params = $this->input();
  147. $this->newDiffParam([
  148. 'filePath' => 'require',
  149. 'bucket' => 'require'
  150. ], $params);
  151. $filePath = (string)($params['filePath']);
  152. $this->setConfig($params['bucket']);
  153. Config::set('ALIYUN_OSS_BUCKET', (string)($params['bucket']));
  154. $ossService = new OssServiceV2((string)($params['bucket']));
  155. //重试3次
  156. $times = 3;
  157. $message = '';
  158. while ($times--) {
  159. try {
  160. $exist = $ossService->fileExist($filePath);
  161. if (true !== $exist) {
  162. $this->output([], 'filePath is not exist');
  163. }
  164. $result = $ossService->fileDelete($filePath);
  165. if ($result) {
  166. $this->output([], 'del success');
  167. } else {
  168. $this->output(['times' => $times], 'del fail');
  169. }
  170. } catch (Exception $ex) {
  171. $message = $ex->getMessage();
  172. continue;
  173. }
  174. }
  175. $this->output(['times' => $times], 'del fail: ' . $message);
  176. }
  177. /**
  178. * 图片信息
  179. */
  180. public function imageInfo() {
  181. $params = $this->input();
  182. $this->newDiffParam([
  183. 'imagePath' => 'require',
  184. 'ossDomain' => 'require',
  185. 'bucket' => 'require',
  186. ], $params);
  187. $imagePath = (string)($params['imagePath']);
  188. Config::set('ALIYUN_OSS_BUCKET', (string)($params['bucket']));
  189. $this->setConfig($params['bucket']);
  190. $ossService = new OssServiceV2((string)($params['bucket']));
  191. //重试3次
  192. $times = 3;
  193. $message = '';
  194. while ($times--) {
  195. try {
  196. $exist = (bool) $ossService->fileExist($imagePath);
  197. if (true !== $exist) {
  198. $this->output([], 'image is not exist');
  199. }
  200. $result = $ossService->imageInfo($imagePath, (string)($params['ossDomain']));
  201. if ($result) {
  202. $this->output($result, 'success');
  203. } else {
  204. $this->output(['times' => $times], 'fail');
  205. }
  206. } catch (Exception $ex) {
  207. $message = $ex->getMessage();
  208. continue;
  209. }
  210. }
  211. $this->output(['times' => $times], 'fail: ' . $message);
  212. }
  213. /**
  214. * 文件是否存在
  215. */
  216. public function fileExist() {
  217. $params = $this->input();
  218. $this->newDiffParam([
  219. 'filePath' => 'require',
  220. 'bucket' => 'require'
  221. ], $params);
  222. $filePath = (string)($params['filePath']);
  223. Config::set('ALIYUN_OSS_BUCKET', (string)($params['bucket']));
  224. $this->setConfig($params['bucket']);
  225. $ossService = new OssServiceV2((string)($params['bucket']));
  226. //重试3次
  227. $times = 3;
  228. $message = '';
  229. while ($times--) {
  230. try {
  231. $result = $ossService->fileExist($filePath);
  232. if ($result) {
  233. $this->output([], 'success');
  234. } else {
  235. $this->output(['times' => $times], 'fail');
  236. }
  237. } catch (Exception $ex) {
  238. $message = $ex->getMessage();
  239. continue;
  240. }
  241. }
  242. $this->output(['times' => $times], 'fail: ' . $message);
  243. }
  244. /**
  245. * bucket列表
  246. */
  247. public function bucketList() {
  248. $ossService = new OssServiceV2();
  249. //重试3次
  250. $times = 3;
  251. $message = '';
  252. while ($times--) {
  253. try {
  254. $bucketList = $ossService->bucketList();
  255. $this->output($bucketList, 'success');
  256. } catch (Exception $ex) {
  257. $message = $ex->getMessage();
  258. continue;
  259. }
  260. }
  261. $this->output(['times' => $times], 'fail: ' . $message);
  262. }
  263. /**
  264. * 获取带有签名的路径
  265. */
  266. public function getSignUrl() {
  267. $params = $this->input();
  268. $this->newDiffParam([
  269. 'object' => 'require',
  270. 'bucket' => 'require',
  271. 'isIntranet' => 'boolean' //是否是内网
  272. ], $params);
  273. $this->setConfig($params['bucket']);
  274. $url = (new OssServiceV2($params['bucket']))->getSignUrl($params);
  275. $this->output(['url' => $url]);
  276. }
  277. /**
  278. * 批量获取带有签名的路径
  279. */
  280. public function getMultiSignUrl() {
  281. $params = $this->input();
  282. $this->newDiffParam(['data' => 'require|array'], $params);
  283. $data = (new OssServiceV2())->getMultiSignUrl($params['data']);
  284. $this->output(['urls' => $data]);
  285. }
  286. /**
  287. * 获取阿里云处理后的图片
  288. */
  289. public function getProcessImageUrl() {
  290. $params = $this->input();
  291. $this->newDiffParam([
  292. 'process' => 'require',
  293. 'object' => 'require',
  294. 'bucket' => 'require',
  295. 'endpoint' => 'require',
  296. ], $params);
  297. $this->setConfig($params['bucket']);
  298. $objectInfo = parse_url($params['object']);
  299. if (empty($objectInfo['path'])) {
  300. $this->output([], '传入的地址信息有误');
  301. }
  302. $params['path'] = $objectInfo['path'];
  303. $data = (new OssServiceV2($params['bucket']))->getProcessImageUrl($params);
  304. $this->output(['url' => $data]);
  305. }
  306. }