xhUploadService.php 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314
  1. <?php
  2. /**
  3. * Created by PhpStorm.
  4. * User: ssh
  5. * Date: 2019/3/13
  6. * Time: 23:26
  7. */
  8. namespace common\services;
  9. use common\components\stringUtil;
  10. use common\components\util;
  11. use Yii;
  12. class xhUploadService
  13. {
  14. /**
  15. * 1:1比例 正方形图片上传
  16. * @author sshaohua
  17. * @time 2019/3/23
  18. */
  19. public static function squareImgUp($sjId)
  20. {
  21. $return = self::imgUp($sjId);
  22. if (isset($return['code']) == false) {
  23. util::fail();
  24. }
  25. if ($return['code'] == 'A0002') {
  26. echo json_encode($return);
  27. Yii::$app->end();
  28. }
  29. $data = $return['data'];
  30. $fileId = $data['fileId'];
  31. $extName = $data['extName'];
  32. $sourcePath = $data['sourcePath'];
  33. $sourceFile = $data['sourceFile'];
  34. $originalUrl = $data['url'];
  35. $outputPath = $data['outputPath'];
  36. $dstImg600 = rtrim($sourcePath, '/') . '/' . $fileId . '_600.' . $extName;
  37. util::img2thumb($sourceFile, $dstImg600, 600, 0, 0, 0);
  38. $bigImg = $outputPath . $fileId . '_600.' . $extName;
  39. $dstImg400 = rtrim($sourcePath, '/') . '/' . $fileId . '_400.' . $extName;
  40. util::img2thumb($sourceFile, $dstImg400, 400, 0, 0, 0);
  41. $middleImg = $outputPath . $fileId . '_400.' . $extName;
  42. $dstImg150 = rtrim($sourcePath, '/') . '/' . $fileId . '_150.' . $extName;
  43. util::img2thumb($sourceFile, $dstImg150, 150, 0, 0, 0);
  44. $smallImg = $outputPath . $fileId . '_150.' . $extName;
  45. return ['originalImg' => $originalUrl, 'middleImg' => $middleImg, 'bigImg' => $bigImg, 'smallImg' => $smallImg];
  46. }
  47. /**
  48. * 3:2比例 长方形图片上传
  49. * @author sshaohua
  50. * @time 2019/3/23
  51. */
  52. public static function rectangleImgUp($sjId)
  53. {
  54. $return = self::imgUp($sjId);
  55. if (isset($return['code']) == false) {
  56. util::fail();
  57. }
  58. if ($return['code'] == 'A0002') {
  59. echo json_encode($return);
  60. Yii::$app->end();
  61. }
  62. $data = $return['data'];
  63. $fileId = $data['fileId'];
  64. $extName = $data['extName'];
  65. $sourcePath = $data['sourcePath'];
  66. $sourceFile = $data['sourceFile'];
  67. $originalUrl = $data['url'];
  68. $outputPath = $data['outputPath'];
  69. $dstImg600 = rtrim($sourcePath, '/') . '/' . $fileId . '_600.' . $extName;
  70. util::img2thumb($sourceFile, $dstImg600, 600, 0, 0, 0);
  71. $bigImg = $outputPath . $fileId . '_600.' . $extName;
  72. $dstImg450 = rtrim($sourcePath, '/') . '/' . $fileId . '_450.' . $extName;
  73. util::img2thumb($sourceFile, $dstImg450, 450, 0, 0, 0);
  74. $middleImg = $outputPath . $fileId . '_450.' . $extName;
  75. $dstImg150 = rtrim($sourcePath, '/') . '/' . $fileId . '_150.' . $extName;
  76. util::img2thumb($sourceFile, $dstImg150, 150, 0, 0, 0);
  77. $smallImg = $outputPath . $fileId . '_150.' . $extName;
  78. return ['originalImg' => $originalUrl, 'middleImg' => $middleImg, 'bigImg' => $bigImg, 'smallImg' => $smallImg];
  79. }
  80. /**
  81. * 焦点图上传
  82. * @author sshaohua
  83. * @time 2019/3/24
  84. */
  85. public static function focusImgUp($sjId)
  86. {
  87. $return = self::imgUp($sjId);
  88. if (isset($return['code']) == false) {
  89. util::fail();
  90. }
  91. if ($return['code'] == 'A0002') {
  92. echo json_encode($return);
  93. Yii::$app->end();
  94. }
  95. $data = $return['data'];
  96. $fileId = $data['fileId'];
  97. $extName = $data['extName'];
  98. $sourcePath = $data['sourcePath'];
  99. $sourceFile = $data['sourceFile'];
  100. $originalUrl = $data['url'];
  101. $outputPath = $data['outputPath'];
  102. $dstImg750 = rtrim($sourcePath, '/') . '/' . $fileId . '_750.' . $extName;
  103. util::img2thumb($sourceFile, $dstImg750, 750, 0, 0, 0);
  104. $middleImg = $outputPath . $fileId . '_750.' . $extName;
  105. $dstImg150 = rtrim($sourcePath, '/') . '/' . $fileId . '_150.' . $extName;
  106. util::img2thumb($sourceFile, $dstImg150, 150, 0, 0, 0);
  107. $smallImg = $outputPath . $fileId . '_150.' . $extName;
  108. return ['originalImg' => $originalUrl, 'middleImg' => $middleImg, 'bigImg' => $middleImg, 'smallImg' => $smallImg];
  109. }
  110. /**
  111. * 取原图,上传什么图就取什么图
  112. * @author sshaohua
  113. * @time 2019/3/24
  114. */
  115. public static function originalImgUp($sjId)
  116. {
  117. $return = self::imgUp($sjId);
  118. if (isset($return['code']) == false) {
  119. util::fail();
  120. }
  121. if ($return['code'] == 'A0002') {
  122. echo json_encode($return);
  123. Yii::$app->end();
  124. }
  125. $data = $return['data'];
  126. $originalUrl = $data['url'];
  127. return ['url' => $originalUrl];
  128. }
  129. /**
  130. * 图片上传
  131. * @author sshaohua
  132. * @time 2019/3/23
  133. */
  134. public static function imgUp($sjId)
  135. {
  136. // Make sure file is not cached (as it happens for example on iOS devices)
  137. header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
  138. header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
  139. header("Cache-Control: no-store, no-cache, must-revalidate");
  140. header("Cache-Control: post-check=0, pre-check=0", false);
  141. header("Pragma: no-cache");
  142. // Support CORS
  143. // header("Access-Control-Allow-Origin: *");
  144. // other CORS headers if any...
  145. if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
  146. exit; // finish preflight CORS requests here
  147. }
  148. if (!empty($_REQUEST['debug'])) {
  149. $random = rand(0, intval($_REQUEST['debug']));
  150. if ($random === 0) {
  151. header("HTTP/1.0 500 Internal Server Error");
  152. exit;
  153. }
  154. }
  155. // header("HTTP/1.0 500 Internal Server Error");
  156. // exit;
  157. // 5 minutes execution time
  158. @set_time_limit(5 * 60);
  159. // Uncomment this one to fake upload time
  160. // usleep(5000);
  161. // Settings
  162. // $targetDir = ini_get("upload_tmp_dir") . DIRECTORY_SEPARATOR . "plupload";
  163. //$targetDir = 'upload_tmp';
  164. //$uploadDir = 'upload';
  165. $targetDir = Yii::getAlias('@webroot') . '/../../images/uploads/' . date('Ym', time()) . '/' . date("d") . '/tmp';
  166. $uploadDir = Yii::getAlias('@webroot') . '/../../images/uploads/' . date('Ym', time()) . '/' . date("d");
  167. $outputPath = '/uploads/' . date('Ym', time()) . '/' . date("d") . '/';
  168. $cleanupTargetDir = true; // Remove old files
  169. $maxFileAge = 5 * 3600; // Temp file age in seconds
  170. // Create target dir
  171. if (!file_exists($targetDir)) {
  172. @mkdir($targetDir, 0777, true);
  173. }
  174. // Create target dir
  175. if (!file_exists($uploadDir)) {
  176. @mkdir($uploadDir, 0777, true);
  177. }
  178. // Get a file name
  179. if (isset($_REQUEST["name"])) {
  180. $fileName = $_REQUEST["name"];
  181. } elseif (!empty($_FILES)) {
  182. $fileName = $_FILES["file"]["name"];
  183. } else {
  184. $fileName = uniqid("file_");
  185. }
  186. $id = stringUtil::buildOrderNo();
  187. $fileId = $id . '_' . $sjId;
  188. $arr = pathinfo($fileName);
  189. $ext = $arr['extension'];
  190. $ext = isset($ext) && !empty($ext) ? $ext : 'jpg';
  191. $fileName = $fileId . '.' . $ext;
  192. $outputFileName = $outputPath . $fileName;
  193. $filePath = $targetDir . DIRECTORY_SEPARATOR . $fileName;
  194. $uploadPath = $uploadDir . DIRECTORY_SEPARATOR . $fileName;
  195. // Chunking might be enabled
  196. $chunk = isset($_REQUEST["chunk"]) ? intval($_REQUEST["chunk"]) : 0;
  197. $chunks = isset($_REQUEST["chunks"]) ? intval($_REQUEST["chunks"]) : 1;
  198. // Remove old temp files
  199. if ($cleanupTargetDir) {
  200. if (!is_dir($targetDir) || !$dir = opendir($targetDir)) {
  201. return ['code' => 'A0002', 'msg' => 'Failed to open temp directory.'];
  202. }
  203. while (($file = readdir($dir)) !== false) {
  204. $tmpfilePath = $targetDir . DIRECTORY_SEPARATOR . $file;
  205. // If temp file is current file proceed to the next
  206. if ($tmpfilePath == "{$filePath}_{$chunk}.part" || $tmpfilePath == "{$filePath}_{$chunk}.parttmp") {
  207. continue;
  208. }
  209. // Remove temp file if it is older than the max age and is not the current file
  210. if (preg_match('/\.(part|parttmp)$/', $file) && (@filemtime($tmpfilePath) < time() - $maxFileAge)) {
  211. @unlink($tmpfilePath);
  212. }
  213. }
  214. closedir($dir);
  215. }
  216. // Open temp file
  217. if (!$out = @fopen("{$filePath}_{$chunk}.parttmp", "wb")) {
  218. return ['code' => 'A0002', 'msg' => 'Failed to open output stream.'];
  219. }
  220. if (!empty($_FILES)) {
  221. if ($_FILES["file"]["error"] || !is_uploaded_file($_FILES["file"]["tmp_name"])) {
  222. return ['code' => 'A0002', 'msg' => 'Failed to move uploaded file.'];
  223. }
  224. // Read binary input stream and append it to temp file
  225. if (!$in = @fopen($_FILES["file"]["tmp_name"], "rb")) {
  226. return ['code' => 'A0002', 'msg' => 'Failed to open input stream.'];
  227. }
  228. } else {
  229. if (!$in = @fopen("php://input", "rb")) {
  230. return ['code' => 'A0002', 'msg' => 'Failed to open input stream.'];
  231. }
  232. }
  233. while ($buff = fread($in, 4096)) {
  234. fwrite($out, $buff);
  235. }
  236. @fclose($out);
  237. @fclose($in);
  238. rename("{$filePath}_{$chunk}.parttmp", "{$filePath}_{$chunk}.part");
  239. $index = 0;
  240. $done = true;
  241. for ($index = 0; $index < $chunks; $index++) {
  242. if (!file_exists("{$filePath}_{$index}.part")) {
  243. $done = false;
  244. break;
  245. }
  246. }
  247. if ($done) {
  248. if (!$out = @fopen($uploadPath, "wb")) {
  249. return ['code' => 'A0002', 'msg' => 'Failed to open output stream.'];
  250. }
  251. if (flock($out, LOCK_EX)) {
  252. for ($index = 0; $index < $chunks; $index++) {
  253. if (!$in = @fopen("{$filePath}_{$index}.part", "rb")) {
  254. break;
  255. }
  256. while ($buff = fread($in, 4096)) {
  257. fwrite($out, $buff);
  258. }
  259. @fclose($in);
  260. @unlink("{$filePath}_{$index}.part");
  261. }
  262. flock($out, LOCK_UN);
  263. }
  264. @fclose($out);
  265. }
  266. return ['code' => 'A0001', 'msg' => 'success', 'data' => [
  267. 'url' => $outputFileName,
  268. 'fileId' => $fileId,
  269. 'extName' => $ext,
  270. 'sourcePath' => $uploadDir,
  271. 'sourceFile' => $uploadPath,
  272. 'outputPath' => $outputPath,
  273. ]];
  274. }
  275. }