FileController.php 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336
  1. <?php
  2. /**
  3. * Created by PhpStorm.
  4. * User: Administrator
  5. * Date: 2017/12/13/013
  6. * Time: 11:04
  7. */
  8. namespace wechat\modules\cp\controllers;
  9. use Yii;
  10. class FileController extends BaseController
  11. {
  12. public $enableCsrfValidation = false;
  13. /**
  14. * 文件保存根路径
  15. * @var string
  16. */
  17. public $basePath = '@webroot';
  18. /**
  19. * 文件保存根url
  20. * @var string
  21. */
  22. public $baseUrl = '@web';
  23. /**
  24. * 文件保存相对路径
  25. * @var string
  26. */
  27. public $savePath = 'upload';
  28. /**
  29. * a list of file name extensions that are allowed to be uploaded.
  30. * 定义允许上传的文件扩展名
  31. * @var array
  32. */
  33. public $extensions = [
  34. 'image' => ['gif', 'jpg', 'jpeg', 'png', 'bmp'],
  35. 'flash' => ['swf', 'flv'],
  36. 'media' => ['swf', 'flv', 'mp3', 'wav', 'wma', 'wmv', 'mid', 'avi', 'mpg', 'asf', 'rm', 'rmvb'],
  37. 'file' => ['doc', 'docx', 'xls', 'xlsx', 'ppt', 'txt', 'zip', 'rar', 'gz', 'bz2', 'pdf'],
  38. ];
  39. /**
  40. * the maximum number of bytes required for the uploaded file.
  41. * 最大文件大小
  42. * @var int
  43. */
  44. private $_maxSize = 1000000;
  45. /**
  46. * the root directory of the file manager.
  47. * 根目录路径,可以指定绝对路径,比如 /var/www/attached/
  48. * @var string
  49. */
  50. public $rootPath = '@webroot/upload';
  51. /**
  52. * 根目录URL,可以指定绝对路径,比如 http://www.yoursite.com/attached/
  53. * @var string
  54. */
  55. public $rootUrl = '@web/upload';
  56. /**
  57. * the sort definition for this file manager.
  58. * 排序
  59. * @var string
  60. */
  61. public $order = 'name';
  62. public function actionUpload()
  63. {
  64. $base_path = rtrim(Yii::getAlias($this->basePath), '\\/') . '/';
  65. $base_url = rtrim(Yii::getAlias($this->baseUrl), '\\/') . '/';
  66. //文件保存目录路径
  67. $save_path = $base_path . rtrim($this->savePath, '\\/') . '/';
  68. //文件保存目录URL
  69. $save_url = $base_url . rtrim($this->savePath, '\\/') . '/';
  70. //定义允许上传的文件扩展名
  71. $ext_arr = $this->extensions;
  72. //最大文件大小
  73. $max_size = $this->getMaxSize();
  74. $add_time = date("Ym", time());
  75. //$save_path = realpath($save_path) . '/';
  76. //PHP上传失败
  77. if (!empty($_FILES['imgFile']['error'])) {
  78. switch ($_FILES['imgFile']['error']) {
  79. case '1':
  80. $error = '超过php.ini允许的大小。';
  81. break;
  82. case '2':
  83. $error = '超过表单允许的大小。';
  84. break;
  85. case '3':
  86. $error = '图片只有部分被上传。';
  87. break;
  88. case '4':
  89. $error = '请选择图片。';
  90. break;
  91. case '6':
  92. $error = '找不到临时目录。';
  93. break;
  94. case '7':
  95. $error = '写文件到硬盘出错。';
  96. break;
  97. case '8':
  98. $error = 'File upload stopped by extension。';
  99. break;
  100. case '999':
  101. default:
  102. $error = '未知错误。';
  103. }
  104. $this->alert($error);
  105. }
  106. //有上传文件时
  107. if (empty($_FILES) === false) {
  108. //原文件名
  109. $file_name = $_FILES['imgFile']['name'];
  110. //服务器上临时文件名
  111. $tmp_name = $_FILES['imgFile']['tmp_name'];
  112. //文件大小
  113. $file_size = $_FILES['imgFile']['size'];
  114. //检查文件名
  115. if (!$file_name) {
  116. $this->alert("请选择文件。");
  117. }
  118. //检查目录
  119. if (@is_dir($save_path) === false) {
  120. $this->alert("上传目录不存在。");
  121. }
  122. //检查目录写权限
  123. if (@is_writable($save_path) === false) {
  124. $this->alert("上传目录没有写权限。");
  125. }
  126. //检查是否已上传
  127. if (@is_uploaded_file($tmp_name) === false) {
  128. $this->alert("上传失败。");
  129. }
  130. //检查文件大小
  131. if ($file_size > $max_size) {
  132. $this->alert("上传文件大小超过限制。");
  133. }
  134. //检查目录名
  135. $dir_name = empty($_GET['dir']) ? 'image' : trim($_GET['dir']);
  136. if (empty($ext_arr[$dir_name])) {
  137. $this->alert("目录名不正确。");
  138. }
  139. //获得文件扩展名
  140. $temp_arr = explode(".", $file_name);
  141. $file_ext = array_pop($temp_arr);
  142. $file_ext = trim($file_ext);
  143. $file_ext = strtolower($file_ext);
  144. //检查扩展名
  145. if (in_array($file_ext, $ext_arr[$dir_name]) === false) {
  146. $this->alert("上传文件扩展名是不允许的扩展名。\n只允许" . implode(",", $ext_arr[$dir_name]) . "格式。");
  147. }
  148. //新文件名
  149. $new_file_name = $this->generateUuid() . '.' . $file_ext;
  150. if (!file_exists($save_path.$add_time)) {
  151. mkdir($save_path.$add_time, 0777);
  152. }
  153. //移动文件
  154. $file_path = $save_path .$add_time. '/' . $new_file_name;
  155. if (move_uploaded_file($tmp_name, $file_path) === false) {
  156. $this->alert("上传文件失败。");
  157. }
  158. $file_url = $save_url .$add_time. '/'. $new_file_name;
  159. header('Content-type: text/html; charset=UTF-8');
  160. echo json_encode(['error' => 0, 'url' => $file_url]);
  161. exit;
  162. }
  163. }
  164. /**
  165. * 生成唯一UUID
  166. */
  167. private function generateUuid()
  168. {
  169. $str = md5(uniqid(mt_rand(), true));
  170. $uuid = substr($str,0,8);
  171. $uuid .= substr($str,8,4);
  172. $uuid .= substr($str,12,4);
  173. $uuid .= substr($str,16,4);
  174. $uuid .= substr($str,20,12);
  175. return $uuid;
  176. }
  177. public function actionFileManager()
  178. {
  179. //根目录路径,可以指定绝对路径,比如 /var/www/attached/
  180. $root_path = rtrim(Yii::getAlias($this->rootPath), '\\/') . '/';
  181. //根目录URL,可以指定绝对路径,比如 http://www.yoursite.com/attached/
  182. $root_url = rtrim(Yii::getAlias($this->rootUrl), '\\/') . '/';
  183. //图片扩展名
  184. $ext_arr = !empty($this->extensions['image']) ? $this->extensions['image'] : [];
  185. //目录名
  186. $dir_name = empty($_GET['dir']) ? '' : trim($_GET['dir']);
  187. if ($dir_name !== '' && !isset($this->extensions[$dir_name])) {
  188. echo "Invalid Directory name.";
  189. exit;
  190. }
  191. //根据path参数,设置各路径和URL
  192. if (empty($_GET['path'])) {
  193. $current_path = realpath($root_path) . '/';
  194. $current_url = $root_url;
  195. $current_dir_path = '';
  196. $moveup_dir_path = '';
  197. } else {
  198. $current_path = realpath($root_path) . '/' . $_GET['path'];
  199. $current_url = $root_url . $_GET['path'];
  200. $current_dir_path = $_GET['path'];
  201. $moveup_dir_path = preg_replace('/(.*?)[^\/]+\/$/', '$1', $current_dir_path);
  202. }
  203. //echo realpath($root_path);
  204. //排序形式,name or size or type
  205. $this->order = empty($_GET['order']) ? 'name' : strtolower($_GET['order']);
  206. //不允许使用..移动到上一级目录
  207. if (preg_match('/\.\./', $current_path)) {
  208. echo 'Access is not allowed.';
  209. exit;
  210. }
  211. //最后一个字符不是/
  212. if (!preg_match('/\/$/', $current_path)) {
  213. echo 'Parameter is not valid.';
  214. exit;
  215. }
  216. //目录不存在或不是目录
  217. if (!file_exists($current_path) || !is_dir($current_path)) {
  218. echo 'Directory does not exist.';
  219. exit;
  220. }
  221. //遍历目录取得文件信息
  222. $file_list = array();
  223. if ($handle = opendir($current_path)) {
  224. $i = 0;
  225. while (false !== ($filename = readdir($handle))) {
  226. if ($filename{0} == '.') continue;
  227. $file = $current_path . $filename;
  228. if (is_dir($file)) {
  229. $file_list[$i]['is_dir'] = true; //是否文件夹
  230. $file_list[$i]['has_file'] = (count(scandir($file)) > 2); //文件夹是否包含文件
  231. $file_list[$i]['filesize'] = 0; //文件大小
  232. $file_list[$i]['is_photo'] = false; //是否图片
  233. $file_list[$i]['filetype'] = ''; //文件类别,用扩展名判断
  234. } else {
  235. $file_list[$i]['is_dir'] = false;
  236. $file_list[$i]['has_file'] = false;
  237. $file_list[$i]['filesize'] = filesize($file);
  238. $file_list[$i]['dir_path'] = '';
  239. $file_ext = strtolower(pathinfo($file, PATHINFO_EXTENSION));
  240. $file_list[$i]['is_photo'] = in_array($file_ext, $ext_arr);
  241. $file_list[$i]['filetype'] = $file_ext;
  242. }
  243. $file_list[$i]['filename'] = $filename; //文件名,包含扩展名
  244. $file_list[$i]['datetime'] = date('Y-m-d H:i:s', filemtime($file)); //文件最后修改时间
  245. $i++;
  246. }
  247. closedir($handle);
  248. }
  249. usort($file_list, [$this, 'cmp_func']);
  250. $result = [];
  251. //相对于根目录的上一级目录
  252. $result['moveup_dir_path'] = $moveup_dir_path;
  253. //相对于根目录的当前目录
  254. $result['current_dir_path'] = $current_dir_path;
  255. //当前目录的URL
  256. $result['current_url'] = $current_url;
  257. //文件数
  258. $result['total_count'] = count($file_list);
  259. //文件列表数组
  260. $result['file_list'] = $file_list;
  261. //输出JSON字符串
  262. header('Content-type: application/json; charset=UTF-8');
  263. echo json_encode($result);
  264. exit;
  265. }
  266. /**
  267. * 排序
  268. * @param array $a
  269. * @param array $b
  270. * @return int
  271. */
  272. protected function cmp_func($a, $b)
  273. {
  274. $order = $this->order;
  275. if ($a['is_dir'] && !$b['is_dir']) {
  276. return -1;
  277. } else if (!$a['is_dir'] && $b['is_dir']) {
  278. return 1;
  279. } else {
  280. if ($order == 'size') {
  281. if ($a['filesize'] > $b['filesize']) {
  282. return 1;
  283. } else if ($a['filesize'] < $b['filesize']) {
  284. return -1;
  285. } else {
  286. return 0;
  287. }
  288. } else if ($order == 'type') {
  289. return strcmp($a['filetype'], $b['filetype']);
  290. } else {
  291. return strcmp($a['filename'], $b['filename']);
  292. }
  293. }
  294. }
  295. /**
  296. * @param string $msg
  297. */
  298. protected function alert($msg)
  299. {
  300. header('Content-type: text/html; charset=UTF-8');
  301. echo json_encode(['error' => 1, 'message' => $msg]);
  302. exit;
  303. }
  304. /**
  305. * @return int
  306. */
  307. public function getMaxSize()
  308. {
  309. return $this->_maxSize;
  310. }
  311. /**
  312. * @param int $maxSize
  313. */
  314. public function setMaxSize($maxSize)
  315. {
  316. $this->_maxSize = intval($maxSize);
  317. }
  318. }