thinkphp5.07 资源管理预览+图片裁切

先上效果图

1


2裁切效果图



3 功能包括  创建文件夹,上传, 删除,预览(最新上传的文件在前面哦)

4html部分

需引入文件

bootstrap.css

bootstrap.min.js
cropper.min.css
cropper.min.js
自行上网下载

代码部分

$('body').on('click', '.addimage',function(){
        data_size = $(this).attr("data-size");
        //展示文件管理器信息
        jQuery('#image_system').modal('show', {backdrop: 'static'});

        $.ajax({
            url: "{:url('admin/image/show',['type'=>1])}",
            method: 'GET',
            dataType: 'json',
            success: function(resp)
            {
                $(".modal-content").html(resp);
            }
        });
    })
定义点击addimage弹出预览

type为1 2 3 分别是 图片  视频 pdf三种类型(不需要该业务的可删除并修改php中跟type有关程序)

<div class="modal-header">
	<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
	<h4 class="modal-title">资源管理</h4>
</div>
<div class="modal-body" id = "modal_body">
	<div class="row">
		<div class="col-sm-5"><a href="{:url('admin/image/show',['directory'=>$parent,'type'=>$type])}" data-toggle="tooltip" title="上一级" id="button-parent" class="btn btn-default"><i class="fa fa-level-up"></i></a> <a href="{:url('admin/image/show',['directory'=>$directory,'type'=>$type])}" data-toggle="tooltip" title="刷新" id="button-refresh" class="btn btn-default"><i class="fa fa-refresh"></i></a>
			<button type="button" data-toggle="tooltip" title="上传" id="button-upload" class="btn btn-primary"><i class="fa fa-upload"></i></button>
			<button type="button" data-toggle="tooltip" title="新目录" id="button-folder" class="btn btn-default"><i class="fa fa-folder"></i></button>
			<button type="button" data-toggle="tooltip" title="删除" id="button-delete" class="btn btn-danger"><i class="fa fa-trash-o"></i></button>
		</div>
		<div class="col-sm-7">
			<div class="input-group">
				<input type="text" name="search" value="<?php echo $filter_name; ?>" placeholder="。。。。" class="form-control">
            <span class="input-group-btn">
            <button type="button" data-toggle="tooltip" title="搜索" id="button-search" class="btn btn-primary"><i class="fa fa-search"></i></button>
            </span></div>
		</div>
	</div>
	<hr />
	<div class="row">
	<?php foreach ($images as $image) { ?>

		<div class="col-sm-3 text-center">

			<?php if ($image['type'] == 'directory') { ?>
			<div class="text-center"><a href="{:url('admin/image/show',['directory'=>$image['path'],'type'=>$type])}" class="directory" style="vertical-align: middle;"><i class="fa fa-folder" style="font-size: 6em"></i></a></div>
			<label>
				<input type="checkbox" name="path[]" value="<?php echo $image['path']; ?>" />
				<?php echo $image['name']; ?></label>
			<?php } ?>

			<?php if ($image['type'] == 'image') { ?>
			<a href="<?php echo $image['img_src']; ?>" class="thumbnail" thumb = "<?php echo $image['thumb']; ?>"><img src="<?php echo $image['thumb']; ?>" alt="<?php echo $image['name']; ?>" title="<?php echo $image['name']; ?>" /></a>
			<label>
				<input type="checkbox" name="path[]" value="<?php echo $image['path']; ?>" />
				<?php echo $image['name']; ?></label>
			<?php } ?>

			<?php if ($image['type'] == 'video') { ?>
			<a href="<?php echo $image['file_src']; ?>" class="videonail"><i class="fa-file-video-o" style="font-size: 6em"></i></a>
			<label>
				<input type="checkbox" name="path[]" value="<?php echo $image['path']; ?>" />
				<?php echo $image['name']; ?></label>
			<?php } ?>

			<?php if ($image['type'] == 'pdf') { ?>
			<a href="<?php echo $image['file_src']; ?>" class="pdfnail"><i class="fa-file-pdf-o" style="font-size: 6em"></i></a>
			<label>
				<input type="checkbox" name="path[]" value="<?php echo $image['path']; ?>" />
				<?php echo $image['name']; ?></label>
			<?php } ?>


		</div>

	<?php } ?>
	</div>
</div>

<div class="row" id="imgcopy" style="display: none">
	<div class="col-md-8">

		<strong class="text-primary">截图</strong>
		<br />
		<br />

		<div class="img-container">
			<img src="" class="img-responsive" id="img-responsive" />
		</div>

	</div>
	<div class="col-md-4">

		<strong class="text-primary">预览</strong>
		<br />
		<br />
		<div class="img-shade">
			<div id="img-preview" class="img-preview"></div>
		</div>

		<table class="table table-bordered table-hover">
			<thead>
			<tr>
				<th width="25%">X</th>
				<th width="25%">Y</th>
				<th width="25%">W</th>
				<th width="25%">H</th>
			</tr>
			</thead>
			<tbody>
			<tr>
				<td id="img-1-x">0px</td>
				<td id="img-1-y">0px</td>
				<td id="img-1-w">0px</td>
				<td id="img-1-h">0px</td>
			</tr>
			</tbody>
		</table>

		<a id="crop-img" href="data/crop-image.php" class="btn btn-secondary">确定</a>

	</div>
</div>

<div class="modal-footer" id="modal_footer"><div class="page">{$pagination}</div></div>
<!---->
<script>
	
	function load_image_syatem(url,data) {
		//展示图片管理器信息
		jQuery('#image_system').modal('show', {backdrop: 'static'});

		$.ajax({
			url: url,
			method: 'GET',
			dataType: 'json',
			data:data,
			success: function(resp)
			{
				$(".modal-content").html(resp);
			}
		});
	}

	function getvoidtime(){
		var x=document.getElementById("video_src");
		var num = Math.ceil(x.duration);
		$("#time_out").val(num);
	}

	$('a.videonail').on('click', function(e) {
		e.preventDefault();

		$('#'+data_name).val( $(this).attr('href'));
		$("#video_src").attr('src',$(this).attr('href'));

		$("#"+thumb_id).attr('src',"{$Think.config.defaultbgv}");

		$('#image_system').modal('hide');
		setTimeout("getvoidtime()",2000);

	});


	$('a.pdfnail').on('click', function(e) {
		e.preventDefault();

		$('#'+data_name).val( $(this).attr('href'));

		$("#"+thumb_id).attr('src',"{$Think.config.defaultbgp}");
		$('#image_system').modal('hide');

	});




	$('a.thumbnail').on('click', function(e) {
		e.preventDefault();

//		$('#'+data_name).val( $(this).attr('href'));
//
//		$("#"+thumb_id).attr('src',$(this).attr('thumb'));

		var thumbimg = $(this).attr('thumb');
		$("#modal_body").hide();
		$("#imgcopy").show();


		var img = $(this).attr('href');
		$("#img-responsive").attr('src',img);



		var imgsize = new Array(220,145);
		if(data_size){
			 imgsize = data_size.split(",");
		}

		var aspect_ratio = imgsize[0] / imgsize[1]
		var preview_size = [260, 260/aspect_ratio],



			$image = $(".img-container img"),
			$x = $("#img-1-x"),
			$y = $("#img-1-y"),
			$w = $("#img-1-w"),
			$h = $("#img-1-h");

		// Plugin Initialization
		$image.cropper({
			aspectRatio: aspect_ratio,
			preview: '#img-preview',
			resizable:true,
			autoCropArea:1,
			dragCrop:false,
			done: function(data)
			{
				data.x = parseInt(data.x);
				data.y = parseInt(data.y);
				data.width = parseInt(data.width);
				data.height = parseInt(data.height);
				$x.text( data.x );
				$y.text( data.y );
				$w.text( data.width );
				$h.text( data.height );
			}
		});

		// Preview Image Setup (based on defined crop width and height
		$("#img-preview").css({
			width: preview_size[0],
			height: preview_size[1]
		});

		$("#crop-img").on('click', function(ev)
		{
			ev.preventDefault();
			$.ajax({
				url:"{:url('admin/image/croper')}",
				method: 'GET',
				dataType: 'json',
				data:{ "x": $x.text(), 'y': $y.text(),'w':$w.text(),'h':$h.text(),'img':img},
				success: function(resp)
				{
					if(resp.code == 1){
						$('#'+data_name).val(""+resp.msg);

						$("#"+thumb_id).attr('src',resp.msg);

//						var myVideo = $("#"+thumb_id);//获取video元素
//						var tol = 0;
//
//						myVideo.addEventListener("loadedmetadata", function(){
//							tol = myVideo.duration;//获取总时长
//							$("#"+time_out).val(tol);
//						});


						$('#image_system').modal('hide');
					}else{
						alert(resp.msg);
					}

				}
			});
		});



		//$('#image_system').modal('hide');

	});

	$('.pagination a').on('click', function(e) {
		e.preventDefault();
		load_image_syatem($(this).attr('href'))
	});

	$('a.directory').on('click', function(e) {
		e.preventDefault();
		load_image_syatem($(this).attr('href'))
		//$('#image_system').load($(this).attr('href'));
	});


	$('#button-parent').on('click', function(e) {
		e.preventDefault();
		load_image_syatem($(this).attr('href'))
		//$('#image_system').load($(this).attr('href'));
	});

	$('#button-refresh').on('click', function(e) {
		e.preventDefault();
		load_image_syatem($(this).attr('href'))
		//$('#image_system').load($(this).attr('href'));
	});

	$('input[name=\'search\']').on('keydown', function(e) {
		if (e.which == 13) {
			$('#button-search').trigger('click');
		}
	});

	$('#button-search').on('click', function(e) {
		var url = "{:url('admin/image/show',['directory'=>$directory])}";
		var data = '';
		var filter_name = $('input[name=\'search\']').val();

		if (filter_name) {
			data = {'filter_name' : encodeURIComponent(filter_name)};
		}


		load_image_syatem(url,data);
	});

	$('#button-upload').on('click', function() {
		$('#form-upload').remove();

		$('body').prepend('<form enctype="multipart/form-data" id="form-upload" style="display: none;"><input type="file" multiple="multiple" name="file[]" value="" /></form>');

		$('#form-upload input[name=\'file[]\']').trigger('click');

		if (typeof timer != 'undefined') {
			clearInterval(timer);
		}

		timer = setInterval(function() {
			if ($('#form-upload input[name=\'file[]\']').val() != '') {
				clearInterval(timer);
				$.ajax({
					url: "{:url('admin/image/upload',['directory'=>$directory])}",
					type: 'post',
					dataType: 'json',
					data: new FormData($('#form-upload')[0]),
					cache: false,
					contentType: false,
					processData: false,
					beforeSend: function() {
						$('#button-upload i').replaceWith('<i class="fa fa-circle-o-notch fa-spin"></i>');
						$('#button-upload').prop('disabled', true);
					},
					complete: function() {
						$('#button-upload i').replaceWith('<i class="fa fa-upload"></i>');
						$('#button-upload').prop('disabled', false);
					},
					success: function(json) {
						if (json['error']) {
							alert(json['error']);
						}

						if (json['success']) {
							alert(json['success']);

							$('#button-refresh').trigger('click');
						}
					},
					error: function(xhr, ajaxOptions, thrownError) {
						alert(thrownError + "\r\n" + xhr.statusText + "\r\n" + xhr.responseText);
					}
				});
			}
		}, 500);
	});

	$('#button-folder').popover({
		html: true,
		placement: 'bottom',
		trigger: 'click',
		title: '文件夹名称',
		content: function() {
			html  = '<div class="input-group">';
			html += '  <input type="text" name="folder" value="" placeholder="文件夹名称" class="form-control">';
			html += '  <span class="input-group-btn"><button type="button" title="新目录" id="button-create" class="btn btn-primary"><i class="fa fa-plus-circle"></i></button></span>';
			html += '</div>';

			return html;
		}
	});

	$('#button-folder').on('shown.bs.popover', function() {
		$('#button-create').on('click', function() {
			$.ajax({
				url: '{:url('admin/image/folder',['directory'=>$directory])}',
				type: 'post',
				dataType: 'json',
				data: 'folder=' + encodeURIComponent($('input[name=\'folder\']').val()),
				beforeSend: function() {
					$('#button-create').prop('disabled', true);
				},
				complete: function() {
					$('#button-create').prop('disabled', false);
				},
				success: function(json) {
					if (json['error']) {
						alert(json['error']);
					}

					if (json['success']) {
						alert(json['success']);

						$('#button-refresh').trigger('click');
					}
				},
				error: function(xhr, ajaxOptions, thrownError) {
					alert(thrownError + "\r\n" + xhr.statusText + "\r\n" + xhr.responseText);
				}
			});
		});
	});


	$('#image_system #button-delete').on('click', function(e) {
		if (confirm('确认删除选中资源嘛?')) {
			$.ajax({
				url: '{:url("admin/image/delete")}',
				type: 'post',
				dataType: 'json',
				data: $('input[name^=\'path\']:checked'),
				beforeSend: function() {
					$('#button-delete').prop('disabled', true);
				},
				complete: function() {
					$('#button-delete').prop('disabled', false);
				},
				success: function(json) {
					if (json['error']) {
						alert(json['error']);
					}

					if (json['success']) {
						alert(json['success']);

						$('#button-refresh').trigger('click');
					}
				},
				error: function(xhr, ajaxOptions, thrownError) {
					alert(thrownError + "\r\n" + xhr.statusText + "\r\n" + xhr.responseText);
				}
			});
		}
	});
</script>





程序

<?php
namespace app\admin\controller;
use think\Config;
use think\Controller;
use think\Paginator;
use think\view\driver\Think;

class Image extends Controller
{
    private $uploadurl = '';
    private $jsuploadurl = '';
    public function _initialize(){
        $user = session('userinfo');
        if($user['groupid'] == 1){
            $this->uploadurl = '.'.Config::get('upload');
            $this->jsuploadurl = Config::get('upload');
        }else{
            $this->uploadurl = '.'.Config::get('upload').'/user'.$user['id'];
            $this->jsuploadurl = Config::get('upload').'/user'.$user['id'];
            if(!is_dir($this->uploadurl)){
                mkdir($this->uploadurl, 0777);
                chmod($this->uploadurl, 0777);
            }
        }
        
    }
    public function show()
    {

        //./upload  /a/b;
        $param = request()->param();
        if (isset($param['filter_name'])) {
            $filter_name = rtrim(str_replace(array('../', '..\\', '..', '*'), '', $param['filter_name']), '/');
        } else {
            $filter_name = null;
        }


        $uploadurl = $this->uploadurl;
        $imgtype= '';
        $videotype = '';
        $pdftype = '';
        if(isset($param['type'])){
            if($param['type'] == 1){
                $imgtype = Config::get('img_type');
            }
            if($param['type'] == 2){
                $videotype = Config::get('video_type');
            }
            if($param['type'] == 3){
                $pdftype = Config::get('pdf_type');
            }
        }else{
            $imgtype = Config::get('img_type');
        }



        // Make sure we have the correct directory
        if (isset($param['directory'])) {
            $directory = str_replace('-','/',$param['directory']);
            $directory = $directory.'/';
        } else {
            $directory = null;
        }

        if (isset($param['page'])) {
            $page = $param['page'];
        } else {
            $page = 1;
        }
//a-b-c
        $data['images'] = array();
//echo $uploadurl.'/'.$directory  . $filter_name . '*';exit;
        // Get directories
        $directories = glob($uploadurl.'/'.$directory  . $filter_name . '*', GLOB_ONLYDIR);
        if (!$directories) {
            $directories = array();
        }
        // Get files
        $files = glob($uploadurl.'/'.$directory . $filter_name . '*.{'.$pdftype.','.$videotype.','.$imgtype.'}', GLOB_BRACE);
        $timefile = array();
        $filelist  =array();
        if (!$files) {
            $files = array();
        }else{
            foreach ($files as $k=>$file){
                if(is_file($file)){
                    $timefile[filemtime($file)] = $file;
                }
            }
        }
        krsort($timefile);
        //var_dump($timefile);exit;

        // Merge directories and files
        $images = array_merge($directories, $timefile);

        $image_total = count($images);

        $images = array_splice($images, ($page - 1) * 16, 16);


        $imgtype_arr = explode(',',$imgtype );
        $videotype_arr = explode(',',$videotype );
        foreach ($images as $image) {
            $name = $this->get_basename($image);

            $thumb_name = $this->get_basename($image);
            if (is_dir($image)) {
                $path = $image;

                $path = str_replace($uploadurl.'/','',$path);

                //$path = $directory;
                $path = str_replace('/','-',$path);
                //$path = $path.'-';
                $data['images'][] = array(
                    'name'  => $name,
                    'type'  => 'directory',
                    'path'  => $path,
                );

            } elseif (is_file($image)) {

                if(!in_array(get_extension($thumb_name),$imgtype_arr)){
                    if(!in_array(get_extension($thumb_name),$videotype_arr)){
                        $data['images'][] = array(
                            'name'  => $name,
                            'type'  => 'pdf',
                            'path'  => $image,
                            'file_src' => $this->jsuploadurl.'/'.$directory.$thumb_name,
                        );
                    }else{
                        $data['images'][] = array(
                            'name'  => $name,
                            'type'  => 'video',
                            'path'  => $image,
                            'file_src' => $this->jsuploadurl.'/'.$directory.$thumb_name,
                        );
                    }

                }else{
                    // Find which protocol to use to pass the full image link back
                    $image_class = \think\Image::open($image);
                    $image_class->thumb(150,150 )->save('./thumb/'.$thumb_name);


                    $data['images'][] = array(
                        'thumb' => '/thumb/'.$thumb_name.'?cache='.rand(1,99999),
                        'img_src'=>$this->jsuploadurl.'/'.$directory.$thumb_name,
                        'name'  => $name,
                        'type'  => 'image',
                        'path'  => $image,
                    );
                }

            }
        }
        //上级目录
        $Parent='';
        if (isset($param['directory'])) {

            $Parent = $param['directory'];

            $Parent = explode('-',$Parent );
            array_pop($Parent);
            $Parent = implode('-',$Parent );
        }
        // var_dump($Parent);exit;
// a-b-c
        $this->assign('parent',$Parent);//上级目录
        $this->assign('filter_name',$filter_name);//查找文件名称
        $directory = isset($param['directory']) ? $param['directory'] : '';
        $type = isset($param['type']) ? $param['type'] :'';
        $this->assign('directory',$directory);//刷新

        $this->assign('pagination', $this->pagerender($image_total,16,$page,$directory,$filter_name,$type));

        $this->assign('images',$data['images']);
        $this->assign('type', $type);

        return $this->fetch();
    }

    public function upload() {

        $json = array();
        $param = request()->param();
        $files = $_FILES;

        $uploadurl = $this->uploadurl;
        // Make sure we have the correct directory
        if (isset($param['directory'])) {
            $directory = str_replace('-','/',$param['directory']);
            $directory = $uploadurl.'/'.$directory.'/';

        } else {
            $directory = $uploadurl.'/';
        }
        $date = array();

        //var_dump($files['file']['name']);exit;
        if(!empty($files['file']['name'][0])){

            foreach ($files['file']['name'] as $k=> $name){
                $file = array();
                $file['file']['name'] = $name;
                $file['file']['type'] = $files['file']['type'][$k];
                $file['file']['tmp_name'] = $files['file']['tmp_name'][$k];
                $file['file']['error'] = $files['file']['error'][$k];
                $file['file']['size'] = $files['file']['size'][$k];

                if (!empty($file['file']['name']) && is_file($file['file']['tmp_name'])) {
                    // Sanitize the filename
                    $filename = $this->get_basename(html_entity_decode($file['file']['name'], ENT_QUOTES, 'UTF-8'));

                    // Validate the filename length
                    if ((utf8_strlen($filename) < 2) || (utf8_strlen($filename) > 255)) {
                        $json[$k]['error'] .= '文件错误';
                    }

                    $img_type = Config::get('img_type');
                    $video_type = Config::get('video_type');
                    $pdf_type = Config::get('pdf_type');
                    $allowed = $img_type.','.$video_type.','.$pdf_type;
                    $allowed = explode(',',$allowed );

                    if (!in_array(utf8_strtolower(utf8_substr(strrchr($filename, '.'), 1)), $allowed)) {
                        $json[$k]['error'] = '文件类型错误';
                    }

                    // Allowed file mime types
                    $allowed = array(
                        'image/jpeg',
                        'image/pjpeg',
                        'image/png',
                        'image/x-png',
                        'image/gif',
                        'video/mp4',
                        'application/pdf'
                    );

                    if (!in_array($file['file']['type'], $allowed)) {
                        $json[$k]['error'] = '文件类型错误,不支持'.$file['file']['type'];
                    }

                    // Return any upload error
                    if ($file['file']['error'] != UPLOAD_ERR_OK) {
                        $json[$k]['error'] =  $file['file']['error'];
                    }
                } else {
                    $json[$k]['error'] = $file['file']['error'];
                }


                if (!isset($json[$k])) {
                    try {
                        move_uploaded_file($file['file']['tmp_name'], $directory. $filename);
                        touch($directory. $filename,time()+$k);
                        //$json['success'] .= $filename.'上传成功/';
                    } catch (Exception $e) {
                        $json[$k]['error'] = $e->getMessage();
                    }
                }

                if(isset($json[$k]['error'])){
                    if(isset($date['error'])){
                        $date['error'] .= $filename.'上传失败,原因:'.$json[$k]['error'];
                    }else{
                        $date['error'] = $filename.'上传失败,原因:'.$json[$k]['error'];
                    }
                }
            }
        }

        if(!isset($date['error'])){
            $date['success'] = '上传成功';
        }
        exit(json_encode($date));
        //$this->response->setOutput(json_encode($json));
    }
    /*
     * @node 创建目录
     * @author 32个字符
     */
    function folder(){

        $json = array();
        $param = request()->param();

        $uploadurl = $this->uploadurl;
        // Make sure we have the correct directory
        if (isset($param['directory'])) {
            $directory = str_replace('-','/',$param['directory']);
            $directory = $uploadurl.'/'.$directory;

        } else {
            $directory = $uploadurl;
        }


        // Check its a directory
        if (!is_dir($directory)) {
            $json['error'] = '路径错误';
        }

        if (!$json) {
            // Sanitize the folder name
            setlocale(LC_ALL, 'zh_CN');
            //echo $this->get_basename(html_entity_decode($param['folder'], ENT_QUOTES, 'UTF-8'));
            //exit;
            $folder = str_replace(array('../', '..\\', '..'), '', basename(html_entity_decode($param['folder'], ENT_QUOTES, 'UTF-8')));
            $folder = str_replace(array('../', '..\\', '..'), '', $this->get_basename(html_entity_decode($param['folder'], ENT_QUOTES, 'UTF-8')));

            if(strpos($folder, ' ') || strpos($folder, '+') || strpos($folder, '/') || strpos($folder, '.') || strpos($folder, '?') || strpos($folder, '%') || strpos($folder, '#') || strpos($folder, '-') || strpos($folder, '&') || strpos($folder, '=')){
                $json['error'] = '文件夹名称不可包含特殊字符:空格+-/?%#&=.';
            }
            // Validate the filename length
            if ((utf8_strlen($folder) < 2) || (utf8_strlen($folder) > 128)) {
                $json['error'] = '名字长度错误';
            }

            // Check if directory already exists or not
            if (is_dir($directory . '/' . $folder)) {
                $json['error'] = '文件夹已存在';
            }
        }

        if (!$json) {
            mkdir($directory . '/' . $folder, 0777);
            chmod($directory . '/' . $folder, 0777);

            $json['success'] = '创建成功';
        }
        exit(json_encode($json));
    }

    public function delete() {

        $json = array();
        $param = request()->param();
        $uploadurl = $this->uploadurl;

        if (isset($param['path'])) {
            $paths = $param['path'];
        } else {
            $paths = array();
        }

        // Loop through each path to run validations
        foreach ($paths as $path) {
            // Check path exsists
            if ($path == $uploadurl.'/') {
                $json['error'] = '根目录无法删除';

                break;
            }
        }

        if (!$json) {
            // Loop through each path
            foreach ($paths as $path) {
                // If path is just a file delete it
                if (is_file($path)) {
                    unlink($path);

                    // If path is a directory beging deleting each file and sub folder
                } else {
                    $path = $uploadurl.'/'.str_replace('-','/' ,$path );


                    if(is_dir($path)){
                        $files = array();

                        // Make path into an array
                        $path = array($path . '*');

                        // While the path array is still populated keep looping through
                        while (count($path) != 0) {
                            $next = array_shift($path);

                            foreach (glob($next) as $file) {
                                // If directory add to path array
                                if (is_dir($file)) {
                                    $path[] = $file . '/*';
                                }

                                // Add the file to the files to be deleted array
                                $files[] = $file;
                            }
                        }

                        // Reverse sort the file array
                        rsort($files);

                        foreach ($files as $file) {
                            // If file just delete
                            if (is_file($file)) {
                                unlink($file);

                                // If directory use the remove directory function
                            } elseif (is_dir($file)) {

                                rmdir($file);
                            }
                        }
                    }

                }
            }

            $json['success'] = '删除成功';
        }
        exit(json_encode($json));
    }


    public function pagerender($total,$limit,$page,$directory,$filter_name,$type) {

        if ($page < 1) {
            $page = 1;
        }

        if (!(int)$limit) {
            $limit = 10;
        }

        $num_links = 8;
        $num_pages = ceil($total / $limit);

        $output = '';

        if ($page > 1) {
            //$output .= '<a class="pageUp" href="' . str_replace('{page}', 1, $this->url) . '">' . $this->text_first . '</a>';
            $output .= '<li><a class="pageUp"  href="' . url('admin/image/show',['page'=>$page-1,'directory'=>$directory,'filter_name'=>$filter_name,'type'=>$type]) . '">' . '«' . '</a></li>';
        }

        if ($num_pages > 1) {
            if ($num_pages <= $num_links) {
                $start = 1;
                $end = $num_pages;
            } else {
                $start = $page - floor($num_links / 2);
                $end = $page + floor($num_links / 2);

                if ($start < 1) {
                    $end += abs($start) + 1;
                    $start = 1;
                }

                if ($end > $num_pages) {
                    $start -= ($end - $num_pages);
                    $end = $num_pages;
                }
            }

            for ($i = $start; $i <= $end; $i++) {
                if ($page == $i) {
                    $output .= '<li class="active"><span>' . $i . '</span></li>';
                } else {
                    $output .= '<li><a href="' . url('admin/image/show',['page'=>$i,'directory'=>$directory,'filter_name'=>$filter_name,'type'=>$type]) . '">' . $i . '</a></li>';
                }
            }
        }

        if ($page < $num_pages) {
            $output .= '<li><a class="pageDown" href="' .url('admin/image/show',['page'=>$page+1,'directory'=>$directory,'filter_name'=>$filter_name,'type'=>$type]) . '">' . '»' . '</a></li>';
            //$output .= '<a class="pageDown" href="' . str_replace('{page}', $num_pages, $this->url) . '">' . $this->text_last . '</a>';
        }

        $output .= '';
        $output = '<ul class="pagination">'.$output.'</ul>';
        if ($num_pages > 1) {
            return $output;
        } else {
            return '';
        }
    }

    function croper(){

        ini_set('memory_limit','300M');
        $param = request()->param();
        $x = isset($param['x']) ? $param['x'] : '' ;
        $y = isset($param['y']) ? $param['y'] : '' ;
        $w = isset($param['w']) ? $param['w'] : '' ;
        $h = isset($param['h']) ? $param['h'] : '' ;

        $imgsrc = isset($param['img']) ? urldecode($param['img']) : '' ;
        if($x == '' || $y== '' || $w == '' || $h == '' || $imgsrc == ''){
            $this->error('参数错误');
        }else{

            $imgname = basename($imgsrc);
            $fname = $w.'_'.$h.'_'.rand(1,9999).$imgname;
            $thname = './croper/'.$fname;
            $rhname = '/croper/'.$fname;
            $temp = array(1=>'gif', 2=>'jpeg', 3=>'png');


            list($fw, $fh, $tmp) = getimagesize('.'.$imgsrc);

            if(!$temp[$tmp]){
                $this->error('该图片类型不匹配');
            }

            $tmp = $temp[$tmp];
            $infunc = "imagecreatefrom$tmp";
            $outfunc = "image$tmp";
            $fimg = $infunc('.'.$imgsrc);

            $timg = @imagecreatetruecolor($w, $h);


            $color = imagecolorAllocate($timg,255,255,255);
            imagefill($timg,0,0,$color);

            imagecopyresampled($timg, $fimg,0,0, $x,$y, $w,$h,$w,$h);
            if($outfunc($timg, $thname)){
                $this->success($rhname);
            }else{
                $this->error('裁图失败,重新裁图');
            }

        }


        //1原图  2缩略图  3截图
        //指定图片位置
    }
    function get_basename($filename){
        return preg_replace('/^.+[\\\\\\/]/', '', $filename);
    }

}

文件类型有三种

不同用户看到不同文件夹分别是 user1 user2等



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
在使用thinkphp框架进行图片上传时,可以通过js来实现以下步骤。 首先,需要创建一个表单,包括一个文件输入框和一个上传按钮。给文件输入框和上传按钮分别设置一个唯一的id值,便于之后通过js获取它们的元素。 接着,使用js来监听上传按钮的点击事件,当点击上传按钮时,触发上传文件的操作。可以通过getElementById方法获取文件输入框的元素,进而获取用户选择的文件对象。 然后,通过FormData对象创建一个表单数据对象,并使用append方法将文件对象添加到表单数据对象中。注意,需要为文件对象添加一个key值,方便后端通过$_FILES数组获取上传的文件。 接下来,通过XMLHttpRequest对象创建一个异步请求对象。使用open方法指定请求方法和URL,并将请求方法设置为POST。注意,这里的URL是指向thinkphp框架中上传图片的控制器方法。 然后,设置请求的header头信息,将Content-Type设置为multipart/form-data,以支持上传文件。 接着,设置请求的回调函数,当请求完成时执行相应的操作。可以在回调函数中验证返回的状态码和响应信息,以确保上传成功。 最后,调用send方法发送请求,并等待上传的过程完成。在上传过程中,可以通过onprogress事件监听上传的进度。 综上所述,通过以上步骤,使用js可以将图片上传到thinkphp框架中。在后端控制器方法中,可以通过$_FILES数组获取上传的文件,并进行相应的处理。这样就实现了js上传图片的功能。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值