jizhicms 个人中心头像上传裁切插件cropperjs的应用

曹え 5811 发布于:2024-10-30 02:32:02

不知道有这个插件,是让ai写的一个插件使用代码,自己修改一下就可以用了,非常不错

插件说明

上传接口是自定义写的,头像会覆盖原来的头像,根据用户的id编号

html代码

<style>
    .upimg {margin-left:100px; border:1px solid #eee; background:#f6f6f6; padding:10px; margin-bottom:20px;}
    </style>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/cropperjs/1.5.12/cropper.min.css">
<div class="form-control">
		              <label for="litpic">会员头像:</label>
		              <div> 
		              <span class="view_img_litpic" style="border:1px solid #eee; display:inline-block;"><img src="{$member['litpic']}" height="100" width="100" /></span><br>
		              <input name="litpic" type="hidden" id="file_url_litpic" value="{$member['litpic']}">
		              </div>
		        </div>
	<div class="upimg">	 
				
	<input type="file" id="fileInput" accept="image/*">
	
    <div style="width:400px;">
        <img id="image" src="" alt="Picture" style="display:none;">
    </div>
    
    <a href="javascript:;" id="uploadBtn" class="layui-btn" style="margin-top:10px; display:none;">确定选中</a>
    </div>	
<script src="https://cdnjs.cloudflare.com/ajax/libs/cropperjs/1.5.12/cropper.min.js"></script>
    <script>
        $(document).ready(function() {
            var fileInput = $('#fileInput');
            var image = $('#image');
            var uploadBtn = $('#uploadBtn');
            var cropper;

            // 选择图片后预览并初始化裁剪器
            fileInput.on('change', function(event) {
                var file = event.target.files[0];
                var reader = new FileReader();

                reader.onload = function(e) {
                    image.show(0)
                    uploadBtn.show(0)
                    image.attr('src', e.target.result);
                    if (cropper) {
                        cropper.destroy();
                    }
                    cropper = new Cropper(image[0], {
                        aspectRatio: 1, // 正方形裁剪区域
                        viewMode: 1, // 限制裁剪区域在图片内部
                        dragMode: 'move', // 拖动模式
                        autoCropArea: 0.8, // 初始裁剪区域大小
                        cropBoxMovable: true, // 允许移动裁剪框
                        cropBoxResizable: true // 允许调整裁剪框大小
                    });
                };

                reader.readAsDataURL(file);
            });

            // 上传头像
            uploadBtn.on('click', function() {
                if (cropper) {
                    cropper.getCroppedCanvas().toBlob(function(blob) {
                        var formData = new FormData();
                        formData.append('file_litpic', blob, 'avatar.png');
				        formData.append("filename",'file_litpic');

                        $.ajax({
                            url: '/user/uploads.html', // 替换为你的上传接口地址
                            type: 'POST',
                            data: formData,
                            processData: false,
                            contentType: false,
                            success: function(response) {
                                var jsonResponse = JSON.parse(response);
                                console.log(jsonResponse);
                                if(jsonResponse.code==0){
        				          var result = "";
        				          result +='<img src="' + jsonResponse["url"] + '?'+ Date.now() +'" height="100"  />';
        				          $(".view_img_litpic").html(result);
        				          $("#file_url_litpic").val(jsonResponse["url"]);
        				        }else{
        				          alert(jsonResponse.error);
        				        }
                            },
                            error: function(error) {
                                alert('头像上传失败,请重试。');
                            }
                        });
                    });
                }
            });
        });
    </script>


php上传接口代码

function uploads(){
		$this->checklogin();
		$file = $this->frparam('filename',1);
		if ($_FILES[$file]["error"] > 0){
		  $data['error'] =  "Error: " . $_FILES[$file]["error"];
		  $data['code'] = 1000;
		}else{
		 
		  $pix = explode('.',$_FILES[$file]['name']);
		  $pix = end($pix);
		  //检测是否允许前台上传文件
		  if(!$this->webconf['isopenhomeupload']){
			  $data['error'] =  "Error: ".JZLANG("已关闭前台上传文件功能");
			  $data['code'] = 1;
			  JsonReturn($data);
		  }
		 
			$fileType = webConf('fileType');
			if(strpos($fileType,strtolower($pix))===false   || stripos($pix,'php')!==false){
				$data['error'] =  "Error: ".JZLANG("文件类型不允许上传!");
				$data['code'] = 1;
				JsonReturn($data);
			}
			$fileSize = (int)webConf('fileSize');
			if($fileSize!=0 && ($_FILES[$file]["size"]/1024)>$fileSize){
				$data['error'] =  "Error: ".JZLANG("文件大小超过网站内部限制!");
				$data['code'] = 1;
				JsonReturn($data);
			}
		 
			$home_save_path = 'static/upload/user';  
			if(!file_exists(APP_PATH.$home_save_path)){
				mkdir(APP_PATH.$home_save_path,0777);
			}  
			 
		  
		    $filename =  $home_save_path.'/head_'.$this->member['id'].'.'.$pix;
		  
			if(move_uploaded_file($_FILES[$file]['tmp_name'],$filename)){
				$data['url'] = '/'.$filename;
				$data['code'] = 0;
				if(isset($_SESSION['member'])){
					$userid = $_SESSION['member']['id'];
				}else{
					$userid = 0;
				}
				$filesize = round(filesize(APP_PATH.$filename)/1024,2);
				M('pictures')->add(['litpic'=>'/'.$filename,'addtime'=>time(),'userid'=>$userid,'size'=>$filesize,'path'=>'Home','filetype'=>strtolower($pix),'molds'=>'member']);
				
			}else{
				$data['error'] =  "Error: ".JZLANG("请检查目录")."[".$home_save_path."]".JZLANG("写入权限");
				$data['code'] = 1;
				  
			} 

			  
		  
		  }
		  
		  
		  JsonReturn($data,true);
		  exit;
		  
		
		
	}


觉得有用请点个赞吧!
0 10