UploadController.php 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233
  1. <?php
  2. namespace hd\controllers;
  3. use bizHd\goods\services\CategoryService;
  4. use common\components\business;
  5. use common\components\dirUtil;
  6. use common\components\oss;
  7. use common\components\stringUtil;
  8. use common\components\noticeUtil;
  9. use Yii;
  10. use common\components\util;
  11. use yii\imagine\Image;
  12. class UploadController extends BaseController
  13. {
  14. public $guestAccess = ['save-img', 'save-file'];
  15. //保存图片上传
  16. public function actionSaveFile()
  17. {
  18. $uploadPath = 'uploads';
  19. // 对上传的文件进行多文件夹管理
  20. $rootPath = Yii::$app->request->post('rootPath');
  21. if (!empty($rootPath) && in_array($rootPath, oss::ROOT_PATHS)) {
  22. $uploadPath = $rootPath;
  23. }
  24. $file = $_FILES['file'];
  25. if (!is_uploaded_file($file['tmp_name'])) {
  26. util::fail('please upload img');
  27. }
  28. $mainId = $this->mainId; // 变动:$this->sjId 改为 $this->mainId
  29. if (intval($mainId) == 0) {
  30. Yii::error('------- lose token -------');
  31. noticeUtil::push('save-file 无token进行上传文件');
  32. }
  33. $shopId = $this->shopId;
  34. $month = date("Ym");
  35. $date = date("d");
  36. $path = dirUtil::getImgUploadDir() . "/{$mainId}/{$shopId}/{$month}/{$date}/";
  37. // 检查目录是否存在,如果不存在则尝试创建。
  38. // 使用 @ 抑制 mkdir 在目录已存在时(并发导致)的 warning。
  39. // 如果 mkdir 失败,则再次检查目录是否存在,以区分是并发创建成功还是真的创建失败。
  40. if (!is_dir($path) && !@mkdir($path, 0700, true) && !is_dir($path)) {
  41. throw new \yii\web\ServerErrorHttpException("目录 '{$path}' 创建失败。");
  42. }
  43. $preFileName = stringUtil::uniqueFileName();
  44. $newFile = $preFileName . ".jpg";
  45. $fullPathFile = $path . $newFile;
  46. if (move_uploaded_file($file['tmp_name'], $fullPathFile)) {
  47. $img = "{$uploadPath}/{$mainId}/{$shopId}/{$month}/{$date}/" . $newFile;
  48. oss::uploadImage($img, $fullPathFile);
  49. $data = business::formatUploadImg($img);
  50. $data['shortUrl'] = $img;
  51. $data['smallShortUrl'] = $img . "?x-oss-process=image/resize,l_200";
  52. util::success($data, 'ok');
  53. } else {
  54. util::fail('fail');
  55. }
  56. }
  57. //上传图片接口
  58. public function actionSaveImg()
  59. {
  60. header('Content-type:text/html;charset=utf-8');
  61. $base64 = file_get_contents('php://input');
  62. $base64_image_content = str_replace("content=", "", urldecode($base64));
  63. $categoryIds = Yii::$app->request->post('categoryId', []);
  64. if (!empty($categoryIds)) {
  65. $categoryList = CategoryService::getByIds($categoryIds);
  66. foreach ($categoryList as $cat) {
  67. if ($cat['sjId'] != $this->sjId) {
  68. util::fail('请选择自己的分类');
  69. }
  70. }
  71. }
  72. //匹配出图片的格式
  73. if (preg_match('/^(data:\s*image\/(\w+);base64,)/', $base64_image_content, $result)) {
  74. $type = $result[2];
  75. $sjId = $this->sjId;
  76. $month = date("Ym");
  77. $date = date("d");
  78. $path = dirUtil::getImgUploadDir() . "/{$sjId}/{$month}/{$date}/";
  79. if (!file_exists($path)) {
  80. //检查是否有该文件夹,如果没有就创建,并给予最高权限
  81. mkdir($path, 0700, true);
  82. }
  83. $preFileName = stringUtil::uniqueFileName();
  84. $newFile = $preFileName . ".{$type}";
  85. $fullPathFile = $path . $newFile;
  86. if (file_put_contents($fullPathFile, base64_decode(str_replace($result[1], '', $base64_image_content))) == false) {
  87. util::fail('上传失败!!');
  88. }
  89. $img = "uploads/{$sjId}/{$month}/{$date}/" . $newFile;
  90. $imgInfo = getimagesize($fullPathFile);
  91. $width = $imgInfo[0];
  92. $height = $imgInfo[1];
  93. //如果图片太大,进行压缩,并删除原图
  94. if ($width > 800) {
  95. $newWidth = 800;
  96. $newHeight = ceil((800 * $height) / $width);
  97. $preFileName = stringUtil::uniqueFileName();
  98. $newFile = $preFileName . ".{$type}";
  99. $newFullPathFile = $path . $newFile;
  100. Image::thumbnail($fullPathFile, $newWidth, $newHeight)->save($newFullPathFile, ['quality' => 100]);
  101. $width = $newWidth;
  102. $height = $newHeight;
  103. $img = "uploads/{$sjId}/{$month}/{$date}/" . $newFile;
  104. unlink($fullPathFile);
  105. $fullPathFile = $newFullPathFile;
  106. }
  107. //上传oss 2021.3.18 lqh
  108. oss::uploadImage($img, $fullPathFile);
  109. //生成小图 200px
  110. //$smallWidth = 200;
  111. //$smallHeight = ceil((200 * $height) / $width);
  112. //$smallFullPathFile = $path . $preFileName . '_small.' . $type;
  113. //Image::thumbnail($fullPathFile, $smallWidth, $smallHeight)->save($smallFullPathFile, ['quality' => 100]);
  114. $data = business::formatUploadImg($img);
  115. // if (!empty($categoryIds)) {
  116. // $time = time();
  117. // $data = ['img' => $img, 'sjId' => $sjId, 'name' => '未命名', 'addTime' => $time];
  118. // $pic = PicService::add($data);
  119. // $currentId = $pic['id'];
  120. // $add = [];
  121. // foreach ($categoryIds as $cat) {
  122. // $add[] = ['categoryId' => $cat, 'picId' => $currentId, 'sjId' => $this->sjId];
  123. // }
  124. // PicCategoryService::batchAdd($add);
  125. // }
  126. $data['shortUrl'] = $img;
  127. $data['smallShortUrl'] = $img . "?x-oss-process=image/resize,l_200";
  128. util::success($data);
  129. }
  130. util::fail('上传失败!');
  131. }
  132. //保存图片 ssh 2019.12.20
  133. public function actionSave()
  134. {
  135. header('Content-type:text/html;charset=utf-8');
  136. $base64_image_content = '';
  137. //匹配出图片的格式
  138. if (preg_match('/^(data:\s*image\/(\w+);base64,)/', $base64_image_content, $result)) {
  139. $type = $result[2];
  140. $sjId = 12358;
  141. $month = date("Ym");
  142. $date = date("d");
  143. $path = dirUtil::getImgUploadDir() . "/{$sjId}/{$month}/{$date}/";
  144. if (!file_exists($path)) {
  145. //检查是否有该文件夹,如果没有就创建,并给予最高权限
  146. mkdir($path, 0700, true);
  147. }
  148. $preFileName = stringUtil::uniqueFileName();
  149. $newFile = $preFileName . ".{$type}";
  150. $fullPath = $path . $newFile;
  151. if (file_put_contents($fullPath, base64_decode(str_replace($result[1], '', $base64_image_content))) == false) {
  152. util::fail('上传失败');
  153. }
  154. $img = "/uploads/{$sjId}/{$month}/{$date}/" . $newFile;
  155. $data = business::formatUploadImg($img);
  156. $data['shortUrl'] = $img;
  157. $data['smallShortUrl'] = $img . "?x-oss-process=image/resize,l_200";
  158. util::success($data);
  159. }
  160. }
  161. //删除oss上的图片
  162. public function actionDeleteFile()
  163. {
  164. $filePath = Yii::$app->request->post('filePath');
  165. if(empty($filePath)){
  166. util::fail('参数错误');
  167. }
  168. // 删除前判断文件是否存在
  169. if(!oss::fileExist($filePath)){
  170. Yii::error('file not exist: ' . $filePath);
  171. util::fail('file not exist');
  172. } else {
  173. Yii::info('file exist: ' . $filePath);
  174. }
  175. // 删除OSS文件
  176. try {
  177. // 设置超时时间为15秒
  178. set_time_limit(15);
  179. $startTime = time();
  180. $timeout = 15; // 15秒超时
  181. oss::deleteObject($filePath);
  182. // 检查是否超时
  183. if (time() - $startTime > $timeout) {
  184. throw new \Exception('删除文件操作超时');
  185. }
  186. } catch (\Exception $e) {
  187. util::fail('删除文件失败:' . $e->getMessage());
  188. }
  189. util::success('success');
  190. }
  191. //批量删除oss上的图片
  192. public function actionDeleteFiles()
  193. {
  194. $filePaths = Yii::$app->request->post('filePaths');
  195. if(empty($filePaths) || !is_array($filePaths)){
  196. util::fail('参数错误');
  197. }
  198. foreach($filePaths as $filePath){
  199. if(!oss::fileExist($filePath)){
  200. Yii::error('file not exist: ' . $filePath);
  201. util::fail('file not exist');
  202. } else {
  203. Yii::info('file exist: ' . $filePath);
  204. }
  205. }
  206. // 删除OSS文件
  207. try {
  208. oss::deleteObjects($filePaths);
  209. } catch (\Exception $e) {
  210. util::fail('删除文件失败:' . $e->getMessage());
  211. }
  212. util::success('success');
  213. }
  214. }