Index.php 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209
  1. <?php
  2. namespace addons\qiniu\controller;
  3. use app\common\exception\UploadException;
  4. use app\common\library\Upload;
  5. use app\common\model\Attachment;
  6. use Qiniu\Auth;
  7. use Qiniu\Storage\ResumeUploader;
  8. use Qiniu\Storage\UploadManager;
  9. use think\addons\Controller;
  10. use think\Config;
  11. /**
  12. * 七牛管理
  13. *
  14. */
  15. class Index extends Controller
  16. {
  17. public function _initialize()
  18. {
  19. //跨域检测
  20. check_cors_request();
  21. parent::_initialize();
  22. Config::set('default_return_type', 'json');
  23. }
  24. public function index()
  25. {
  26. Config::set('default_return_type', 'html');
  27. $this->error("当前插件暂无前台页面");
  28. }
  29. /**
  30. * 中转上传文件
  31. * 上传分片
  32. * 合并分片
  33. */
  34. public function upload()
  35. {
  36. Config::set('default_return_type', 'json');
  37. $this->check();
  38. $config = get_addon_config('qiniu');
  39. $config['savekey'] = str_replace(['{year}', '{mon}', '{day}', '{filemd5}', '{.suffix}'], ['$(year)', '$(mon)', '$(day)', '$(etag)', '$(ext)'], $config['savekey']);
  40. // 构建鉴权对象
  41. $auth = new Auth($config['accessKey'], $config['secretKey']);
  42. // 生成上传 Token
  43. $token = $auth->uploadToken($config['bucket'], null, 3600, ['saveKey' => ltrim($config['savekey'], '/')]);
  44. // 初始化 UploadManager 对象并进行文件的上传。
  45. $uploadMgr = new UploadManager();
  46. $chunkid = $this->request->post("chunkid");
  47. if ($chunkid) {
  48. $action = $this->request->post("action");
  49. $chunkindex = $this->request->post("chunkindex/d");
  50. $chunkcount = $this->request->post("chunkcount/d");
  51. $filesize = $this->request->post("filesize");
  52. $filename = $this->request->post("filename");
  53. if ($action == 'merge') {
  54. if ($config['uploadmode'] == 'server') {
  55. $attachment = null;
  56. //合并分片文件
  57. try {
  58. $upload = new Upload();
  59. $attachment = $upload->merge($chunkid, $chunkcount, $filename);
  60. } catch (UploadException $e) {
  61. $this->error($e->getMessage());
  62. }
  63. }
  64. $contexts = $this->request->post("contexts/a", []);
  65. $uploader = new ResumeUploader($token, null, null, $filesize);
  66. list($ret, $err) = $uploader->setContexts($contexts)->makeFile($filename);
  67. if ($err !== null) {
  68. $this->error("上传失败");
  69. } else {
  70. $this->success("上传成功", '', ['url' => '/' . $ret['key'], 'fullurl' => cdnurl('/' . $ret['key'], true), 'hash' => $ret['hash']]);
  71. }
  72. } else {
  73. //默认普通上传文件
  74. $file = $this->request->file('file');
  75. try {
  76. $upload = new Upload($file);
  77. $file = $upload->chunk($chunkid, $chunkindex, $chunkcount);
  78. } catch (UploadException $e) {
  79. $this->error($e->getMessage());
  80. }
  81. //上传分片文件
  82. //$file = $this->request->file('file');
  83. $filesize = $file->getSize();
  84. //合并分片文件
  85. $uploader = new ResumeUploader($token, null, fopen($file->getRealPath(), 'rb'), $filesize);
  86. $ret = $uploader->uploadChunk($chunkindex, $file, $filesize);
  87. $this->success("上传成功", "", $ret);
  88. }
  89. } else {
  90. $attachment = null;
  91. //默认普通上传文件
  92. $file = $this->request->file('file');
  93. try {
  94. $upload = new Upload($file);
  95. $suffix = $upload->getSuffix();
  96. $md5 = md5_file($file->getRealPath());
  97. $search = ['$(year)', '$(mon)', '$(day)', '$(etag)', '$(ext)'];
  98. $replace = [date("Y"), date("m"), date("d"), $md5, '.' . $suffix];
  99. $savekey = ltrim(str_replace($search, $replace, $config['savekey']), '/');
  100. $attachment = $upload->upload($savekey);
  101. } catch (UploadException $e) {
  102. $this->error($e->getMessage());
  103. }
  104. //文件绝对路径
  105. $filePath = $upload->getFile()->getRealPath() ?: $upload->getFile()->getPathname();
  106. //上传到七牛后保存的文件名
  107. $saveKey = ltrim($attachment->url, '/');
  108. try {
  109. // 调用 UploadManager 的 putFile 方法进行文件的上传。
  110. list($ret, $err) = $uploadMgr->putFile($token, $saveKey, $filePath);
  111. if ($err !== null) {
  112. throw new \Exception("上传失败");
  113. }
  114. //成功不做任何操作
  115. } catch (\Exception $e) {
  116. $attachment->delete();
  117. @unlink($filePath);
  118. $this->error("上传失败");
  119. }
  120. $this->success("上传成功", '', ['url' => cdnurl($attachment->url, true), 'fullurl' => cdnurl($attachment->url, true)]);
  121. }
  122. }
  123. /**
  124. * 通知回调
  125. */
  126. public function notify()
  127. {
  128. Config::set('default_return_type', 'json');
  129. $this->check();
  130. $size = $this->request->post('size');
  131. $name = $this->request->post('name');
  132. $hash = $this->request->post('hash', '');
  133. $type = $this->request->post('type');
  134. $width = $this->request->post('width');
  135. $height = $this->request->post('height');
  136. $url = $this->request->post('url');
  137. $suffix = substr($name, stripos($name, '.') + 1);
  138. $attachment = Attachment::where('url', $url)->where('storage', 'qiniu')->find();
  139. if (!$attachment) {
  140. $params = array(
  141. 'admin_id' => (int)session('admin.id'),
  142. 'user_id' => (int)cookie('uid'),
  143. 'filename' => $name,
  144. 'filesize' => $size,
  145. 'imagewidth' => $width,
  146. 'imageheight' => $height,
  147. 'imagetype' => $suffix,
  148. 'imageframes' => 0,
  149. 'mimetype' => $type,
  150. 'url' => cdnurl($url,true),
  151. 'uploadtime' => time(),
  152. 'storage' => 'qiniu',
  153. 'sha1' => $hash,
  154. );
  155. Attachment::create($params);
  156. }
  157. $this->success();
  158. }
  159. /**
  160. * 检查签名是否正确或过期
  161. */
  162. protected function check()
  163. {
  164. $qiniutoken = $this->request->post('qiniutoken', $this->request->server('AUTHORIZATION'), 'trim');
  165. if (!$qiniutoken) {
  166. $this->error("参数不正确");
  167. }
  168. $config = get_addon_config('qiniu');
  169. $auth = new Auth($config['accessKey'], $config['secretKey']);
  170. list($accessKey, $sign, $data) = explode(':', $qiniutoken);
  171. if (!$accessKey || !$sign || !$data) {
  172. $this->error("参数不正确");
  173. }
  174. if ($accessKey !== $config['accessKey']) {
  175. $this->error("参数不正确");
  176. }
  177. if ($accessKey . ':' . $sign !== $auth->sign($data)) {
  178. $this->error("签名不正确");
  179. }
  180. $json = json_decode(\Qiniu\base64_urlSafeDecode($data), true);
  181. if ($json['deadline'] < time()) {
  182. $this->error("请求已经超时");
  183. }
  184. }
  185. }