UploadController.php 8.8 KB

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