123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584 |
- <?php
- declare(strict_types=1);
- /**
- * upload文件管理
- *
- * @version 0.0.0
- * @author by huwhois
- * @time 2017/11/27
- */
- namespace app\sys\controller;
- use Exception;
- use UnexpectedValueException;
- use DirectoryIterator;
- use think\facade\View;
- use think\File;
- use think\Image;
- use think\facade\Config;
- use think\exception\ValidateException;
- use app\common\service\FileService;
- use app\common\model\FileManager as FileManagerModel;
- use think\file\UploadedFile;
- class FileManager extends Base
- {
- protected $modelName = 'FileManager';
- protected $t_suffix = '_thumb';
- protected $width = 400; // 缩略图高度
- protected $height = 300;
- protected $storage_path = 'public/storage';
- public function index()
- {
- $param = $this->request->param();
- $param['limit'] = isset($param['limit']) ? (int) $param['limit'] : Config::get('app.page_size');
- $list = FileManagerModel::queryPage($param);
- View::assign('list', $list);
- return View::fetch();
- }
- /**
- * 浏览文件
- */
- public function explorer()
- {
- $param = $this->request->param();
- $activepath = isset($param['activepath']) ? $param['activepath'] : '';
- $realpath = $this->app->getRootPath() . $this->storage_path . $activepath;
- try {
- $dirhandle = new DirectoryIterator($realpath);
- $dirs = $files = [];
- foreach ($dirhandle as $fileInfo) {
- if($fileInfo->isDot() || $fileInfo->getFilename() == '.gitignore') {
- continue;
- } elseif ($fileInfo->isDir()) {
- $dirs[] = $fileInfo->getFilename();
- } elseif ($fileInfo->isFile()) {
- $files[] = [
- 'filename' => $fileInfo->getFilename(),
- 'extension' => strtolower($fileInfo->getExtension()),
- 'size' => format_bytes($fileInfo->getSize()),
- 'time' => $fileInfo->getCTime(),
- ];
- }
- }
-
- $counts = count($dirs) + count($files);
- $activeurl = preg_replace("#[\/][^\/]*$#i", "", $activepath);
- View::assign([
- 'dirs' => $dirs,
- 'files' => $files,
- 'counts' => $counts,
- 'activeurl' => $activeurl,
- 'activepath' => $activepath,
- ]);
- return View::fetch();
- } catch(UnexpectedValueException $uve) {
- $this->error($uve->getMessage());
- }
- }
- /**
- * 附件上传
- */
- public function uploadFile()
- {
- $activepath = $this->request->has('activepath') ? $this->request->param('activepath') : '';
- $files = $this->request->file('upload_file');
- if ($files) {
- try {
- validate(
- [
- 'file' => [
- // 限制文件大小(单位b),这里限制为10M
- 'fileSize' => 10 * 1024 * 1024,
- // 限制文件后缀,多个后缀以英文逗号分割
- 'fileExt' => 'jpg,png,gif,jpeg,webp,jfif,pdf,doc,docx,xls,xlsx,ppt,pptx,txt'
- ]
- ],
- [
- 'file.fileSize' => '文件太大',
- 'file.fileExt' => '不支持的文件后缀',
- ]
- )->check(['file' => $files]);
- $savenames = [];
- $uploadFiles = [];
-
- if (!is_array($files) && $files instanceof UploadedFile) {
- $uploadFiles[] = $files;
- } else {
- $uploadFiles = $files;
- }
- $url = Config::get('filesystem.disks.public.url');
- foreach ($uploadFiles as $file) {
- $fileinfo = new FileManagerModel();
-
- $fileinfo->title = $file->getOriginalName();
- $fileinfo->filesize = $file->getSize();
- $fileinfo->filetime = $file->getCTime();
- $fileinfo->fileextension = $file->extension();
- $fileinfo->username = $this->getSysUser()->username;
- $fileinfo->hash_md5 = $file->md5();
- if (empty($activepath)) {
- $savename = \think\facade\Filesystem::disk('public')->putFile('/', $file);
-
- $fileinfo->filepath = $url . '/' . $savename;
- $fileinfo->filename = basename($savename);
- } else {
- $savename = $activepath . '/' . $file->hashName();
- $savepath = $this->app->getRootPath() . $this->storage_path . $savename;
-
- $file = $file->move($this->app->getRootPath() . $this->storage_path . $activepath, $savepath);
- $fileinfo->filepath = $url . $savename;
- $fileinfo->filename = $file->hashName();
- }
- $fileinfo->save();
- $savenames[] = $fileinfo->filepath;
- }
- return json(['code' => 0, 'msg'=>'上传成功', 'filename'=>$savenames]);
- } catch (ValidateException $e) {
- $this->error($e->getMessage());
- }
- } else {
- $this->error('图片不能为空');
- }
- }
- /**
- * 修改文件title
- */
- public function updateFileTitle($id = 0, $filetitle = '')
- {
- $fileInfo = FileManagerModel::find($id);
- if ($fileInfo == null) {
- return json(['code'=>1, 'fileid='.$id.'不存在']);
- }
- $fileInfo->title = $filetitle;
- if ($fileInfo->save()) {
- return json(['code'=>0, 'msg'=>'success']);
- } else {
- return json(['code'=>1, 'msg'=>'failed']);
- }
- }
- /**
- * 删除
- * @param int|array $id info id
- * @return array
- */
- public function delete($id)
- {
- if ($this->request->isPost()) {
- $whereOp = '=';
- if (is_array($id)) {
- $whereOp = 'IN';
- }
- $list = FileManagerModel::where('fileid', $whereOp, $id)->select();
- foreach ($list as $value) {
- $file = $this->app->getRootPath() . 'public' . $value->filepath;
- if (file_exists($file)) {
- unlink($file);
- }
- }
-
- if (FileManagerModel::destroy($id)) {
- return ['code' => 0,'msg'=>'删除成功'];
- } else {
- return ['code' => 1,'msg'=>'删除失败'];
- }
- }
- }
- /**
- * 删除空目录
- */
- public function deldir()
- {
- if ($this->request->isPost()) {
- $dir = str_replace('/', DIRECTORY_SEPARATOR, $this->request->param('dir'));
- $dir_name = $this->app->getRootPath() . $this->storage_path . DIRECTORY_SEPARATOR . $dir;
- try {
- rmdir($dir_name);
- return ['code' => 0, 'msg' => 'success'];
- } catch (Exception $e) {
- return ['code' => 1, 'msg' => 'failed, 目录不为空'];
- }
- }
- }
- /**
- * 删除文件
- */
- public function delfile()
- {
- if ($this->request->isPost()) {
- $filename = str_replace('/', DIRECTORY_SEPARATOR, $this->request->param('filename'));
- $filepath = $this->app->getRootPath() . $this->storage_path . DIRECTORY_SEPARATOR . $filename;
- if (unlink($filepath)) {
- return ['code' => 0, 'msg' => 'success'];
- } else {
- return ['code' => 1, 'msg' => 'failed'];
- }
- }
- }
- /**
- * 处理上传的图片
- */
- protected function dealUploadImg(File $file, $water, $thumb, $width, $height, $overwrite)
- {
- $savename = "";
- $thumbname = "";
- if ($water == true || $thumb == true) {
- $image = Image::open($file);
- if ($water) {
- $type = $this->system->water_type ?: Config::get('filesystem.water.type');
- if ($type == 'water') {
- $watemark = $this->system->watermark ?: Config::get('filesystem.water.watermark');
- $image->water($watemark);
- } else {
- $watetext = $this->system->watertext ?: Config::get('filesystem.water.watertext');
- $image->text($watetext, Config::get('filesystem.water.waterfont'), 30, '#ffffff30');
- }
- }
- $savename = $file->hashName();
- $realPath = Config::get('filesystem.disks.public.root') . '/' . $savename;
- if ($thumb == true) {
- if ($overwrite == true) {
- $image->thumb($width, $height, 1);
- $image->save($realPath);
- } else {
- $image->save($realPath);
- $image->thumb($width, $height, 1);
- $ext = $file->extension();
- $thumbname = str_replace('.' . $ext, '', str_replace('\\', '/', $savename)) . $this->t_suffix . '.' . $ext;
- $image->save(Config::get('filesystem.disks.public.root') . '/' . $thumbname);
- }
- } else {
- $image->save($realPath);
- }
- unset($image);
- } else {
- $savename = \think\facade\Filesystem::disk('public')->putFile('/', $file);
- }
- return [
- 'picname' => str_replace('\\', '/', $savename),
- 'thumbname' => $thumbname
- ];
- }
- /**
- * 图片上传(iframe 页面)
- */
- public function uploadimg(string $img_id = 'picture', $water = false, $thumb = false, $width = 400, $height = 300, $overwrite = false)
- {
- View::assign([
- 'img_id' => $img_id,
- 'water' => $water,
- 'thumb' => $thumb,
- 'width' => $width,
- 'height' => $height,
- 'overwrite' => $overwrite
- ]);
- return View::fetch();
- }
- /**
- * 本地图片上传
- * @file upload_file 上传的文件
- * @param string $img_id 图片ipnut text id 默认值 picture
- * @param boolean $water 是否添加水印
- * @param boolean $thumb 是否制作缩略图
- * @param int $width 缩略图最大宽
- * @param int $height 缩略图最大高
- * @param bool $overwrite 生成缩略图后是否保存原图
- */
- public function uploadLocalImg(string $img_id = 'picture', $water = false, $thumb = false, $width = 400, $height = 300, $overwrite = false)
- {
- if ($this->request->isPost()) {
- $file = $this->request->file('upload_file');
- if ($file) {
- try {
- validate(
- [
- 'file' => [
- // 限制文件大小(单位b),这里限制为4M
- 'fileSize' => 4 * 1024 * 1024,
- // 限制文件后缀,多个后缀以英文逗号分割
- 'fileExt' => 'jpg,png,gif,jpeg,webp,jfif'
- ]
- ],
- [
- 'file.fileSize' => '文件太大',
- 'file.fileExt' => '不支持的文件后缀',
- ]
- )->check(['file' => $file]);
-
- $arr = $this->dealUploadImg($file, $water, $thumb, $width, $height, $overwrite);
- return array_merge(
- [
- 'code' => 0,
- 'img_id' => $img_id,
- 'picture_url' => Config::get('filesystem.disks.public.url') . '/'
- ],
- $arr
- );
- } catch (ValidateException $e) {
- $this->error($e->getMessage());
- }
- } else {
- $this->error('图片不能为空');
- }
- }
- }
- /**
- * 网络图片上传
- * @paran string url_file 网络图片地址
- * @param string $img_id 图片ipnut text id 默认值 picture
- * @param boolean $water 是否添加水印
- * @param boolean $thumb 是否制作缩略图
- * @param int $width 缩略图最大宽
- * @param int $height 缩略图最大高
- * @param bool $overwrite 生成缩略图后是否保存原图
- */
- public function uploadUrlImg(string $img_id = 'picture', $water = false, $thumb = false, $width = 400, $height = 300, $overwrite = false)
- {
- if ($this->request->isPost()) {
- $urlImg = $this->request->param('url_file');
- if ($urlImg) {
- try {
- $fileService = new FileService();
- $file = $fileService->downloadUrlImg($urlImg);
- $arr = $this->dealUploadImg($file, $water, $thumb, $width, $height, $overwrite);
- @unlink($file->realPath);
- return array_merge(
- [
- 'code' => 0,
- 'img_id' => $img_id,
- 'picture_url' => Config::get('filesystem.disks.public.url') . '/'
- ],
- $arr
- );
- } catch (\think\exception\ValidateException $e) {
- $this->error($e->getMessage());
- }
- } else {
- $this->error('图片地址不能为空');
- }
- }
- }
- /**
- * 选择服务器图片
- * @paran string online_file 服务器图片地址
- * @param string $img_id 图片ipnut text id 默认值 picture
- * @param boolean $water 是否添加水印
- * @param boolean $thumb 是否制作缩略图
- * @param int $width 缩略图最大宽
- * @param int $height 缩略图最大高
- * @param bool $overwrite 生成缩略图后是否保存原图
- */
- public function uploadonlineimg(string $img_id = 'picture', $water = false, $thumb = false, $width = 400, $height = 300, $overwrite = false)
- {
- if ($this->request->isPost()) {
- $pathImg = $this->request->param('online_file');
- if ($pathImg && file_exists($this->app->getRootPath() . "public" . $pathImg)) {
- $picname = $pathImg;
- $thumbname = "";
- if ($thumb) {
- if (stripos($picname, $this->t_suffix)) {
- $thumbname = $pathImg;
- } else {
- try {
- $file = new File($this->app->getRootPath() . "public" . $pathImg);
- $ext = $file->getExtension();
- $thumbname = str_replace('.' . $ext, '', str_replace('\\', '/', $picname)) . $this->t_suffix . '.' . $ext;
- if (!file_exists($thumbname)) {
- $image = Image::open($file);
- $image->thumb($width, $height, 1);
- $image->save($this->app->getRootPath() . "public" . $thumbname);
- unset($image);
- }
- if ($overwrite) {
- $picname = $thumbname;
- }
- } catch (Exception $e) {
- $this->error($e->getMessage());
- }
- }
- }
- return [
- 'code' => 0,
- 'img_id' => $img_id,
- 'picname' => $picname,
- 'thumbname' => $thumbname,
- ];
- } else {
- $this->error('图片地址不存在');
- }
- }
- }
- public function onlineimg($page)
- {
- $files = FileService::getFiles(Config::get('filesystem.disks.public.root'));
- if (!count($files)) {
- return json_encode(array(
- "state" => "no match file",
- "list" => array(),
- "start" => $page,
- "total" => count($files)
- ));
- }
- /* 获取指定范围的列表 */
- $page = $page - 1 < 0 ? 0 : (int)$page - 1;
- $size = 20;
- $start = $page * $size;
- $end = $start + $size;
- $len = count($files);
- for ($i = min($end, $len) - 1, $list = array(); $i < $len && $i >= 0 && $i >= $start; $i--) {
- $list[] = $files[$i];
- }
- return json([
- "code" => 0,
- "list" => $list,
- "page" => $page + 1,
- "total" => count($files)
- ]);
- }
- /**
- * 判断(远程)文件是否为图片
- */
- // public function isImg()
- // {
- // if ($this->request->isAjax()) {
- // $filename = $this->request->param('filename');
- // $res = \mylib\GetImageByurl::isImg($filename);
- // if (!$res) {
- // $this->error('该图片不合法');
- // } else {
- // return ['code'=>2,'msg'=>'图片地址可用'];
- // }
- // }
- // }
- /**
- * ckeditor 富文本编辑器上传图片
- */
- public function ckeditorUploadImage()
- {
- if ($this->request->isPost()) {
- $file = $this->request->file('upload');
- if ($file) {
- try {
- validate(
- [
- 'file' => [
- // 限制文件大小(单位b),这里限制为4M
- 'fileSize' => 4 * 1024 * 1024,
- // 限制文件后缀,多个后缀以英文逗号分割
- 'fileExt' => 'jpg,png,gif,jpeg,webp,jfif'
- ]
- ],
- [
- 'file.fileSize' => '文件太大',
- 'file.fileExt' => '不支持的文件后缀',
- ]
- )->check(['file' => $file]);
- $savename = \think\facade\Filesystem::disk('public')->putFile('/', $file);
- return json([
- 'uploaded' => 1,
- 'fileName' => basename($savename),
- 'url' => Config::get('filesystem.disks.public.url') . '/' . $savename
- ]);
- } catch (\think\exception\ValidateException $e) {
- $this->error($e->getMessage());
- return json([
- 'uploaded' => 1,
- 'error' => ['message' => $e->getMessage()]
- ]);
- }
- } else {
- return json([
- 'uploaded' => 1,
- 'error' => ['message' => '图片不能为空']
- ]);
- }
- }
- }
- }
|