富文本编辑器kindeditor批量上传图片并生成缩略图

一、使用富文本编辑器kindeditor需引入文件如下:

<script charset="utf-8" src="<%=path %>/skin/js/kindeditor/kindeditor-all.js"></script>
<script charset="utf-8" src="<%=path %>/skin/js/kindeditor/lang/zh-CN.js"></script>

二、编辑器初始化

K.create('textarea[name="nr"]'中的name要使用页面中textarea 的name

urlType:定义了上传图片的相对路径其他参数(”absolute”、”domain”),默认为“”

item:定义显示的各个小图标

uploadJson:定义请求的后台地址

filePostName:注意这个参数他表示图片的name,后台接受的时候一定要名字一样

allowImageUpload:设置为true

<script type="text/javascript">
var editor;
KindEditor.ready(function(K) {
	editor = K.create('textarea[name="nr"]', {
		//resizeType : 1,
		urlType:"relative",
		items : [
	        'source', '|', 'undo', 'redo', '|', 'preview', 'print', 'template', 'code', 'cut', 'copy', 'paste',
	        'plainpaste', 'wordpaste', '|', 'justifyleft', 'justifycenter', 'justifyright',
	        'justifyfull', 'insertorderedlist', 'insertunorderedlist', 'indent', 'outdent', 'subscript',
	        'superscript', 'clearhtml', 'quickformat', 'selectall', '|', 'fullscreen', '/',
	        'formatblock', 'fontname', 'fontsize', '|', 'forecolor', 'hilitecolor', 'bold',
	        'italic', 'underline', 'strikethrough', 'lineheight', 'removeformat', '|', 'multiimage',
	         'table', 'hr', 'emoticons', 'baidumap', 'pagebreak',
	        'anchor', 'link', 'unlink', '|', 'about'
	         ],
		uploadJson : context+"/xinwen/upload" ,//后台上传调用方法地址,返回json格式
		filePostName: 'imgFiles',//类似于定义input的name
		//allowPreviewEmoticons : true,
		 allowImageUpload : true,
        afterCreate : function() {
            var self = this;
        },
        afterBlur:function(){this.sync();},
		
	});
});		




</script>

三、html代码

 <textarea id="addeditor_id" name="nr" style="width:58%;height:600px;border: 0 none;  visibility:hidden;"></textarea>

四、java后台

       /**
	     * 文件上传公共方法
	     * 
	     * @param response
	     * @param request
	     * @param imgFile
	     *            单文件
	     * @return
	     */
	    public Map<String, Object> uploadImg(HttpServletResponse response, HttpServletRequest request,
	            MultipartFile imgFile) {
	        response.setContentType("text/plain;charset=UTF-8");
	        Map<String, Object> map = new HashMap<String, Object>();
	        // 文件保存目录URL
	        //String saveUrl = "upload/img/";
	       // String saveUrl = "upload/";
	        String saveUrl = request.getServletContext().getRealPath("/upload//");
	         //String saveUrl = request.getServletContext().getContextPath();
	        // 最大文件大小
	        long maxSize = 102400000;

	        if (imgFile == null) {
	            return returnErrorMap("请选择文件!");
	        }
	        String imgFileFileName = imgFile.getOriginalFilename();
	        String fileType = imgFileFileName.substring(imgFileFileName.lastIndexOf(".") + 1).toLowerCase();// 文件类型
	        Map<String, String> fileTypeMap = new HashMap<String, String>();
	        fileTypeMap.put("image", "gif,jpg,jpeg,png,bmp");
	        if (fileTypeMap.containsKey(fileType)) {
	            return returnErrorMap("上传文件扩展名[" + fileType + "]是不允许的扩展名。");
	        }
	        if (imgFile.getSize() > maxSize) {
	            return returnErrorMap(
	                    "[ " + imgFileFileName + " ]超过单个文件大小限制,文件大小[ " + imgFile.getSize() + " ],限制为[ " + maxSize + " ] ");
	        }
	        String newFileName =  UUID.randomUUID().toString().replaceAll("-","") + "." + fileType;// 重新命名
	        try {
	            FileUtils.copyInputStreamToFile(imgFile.getInputStream(), new File(saveUrl+"\\"+newFileName));// 生成文件
	            System.out.println(saveUrl+"\\"+newFileName);
	            map.put("url","\\upload\\"+newFileName);
	            map.put("error", "0");
	            return map;
	        } catch (Exception e) {
	            return returnErrorMap("图片上传失败");
	        }
	    }

	    /**
	     * 
	     * @param response
	     * @param request
	     * @param imgFiles
	     *            多文件
	     * @return
	     */
	     @RequestMapping("/upload")
	      @ResponseBody
	     public  String uploadImgs(HttpServletResponse response, HttpServletRequest request,
	            @RequestParam("imgFiles") MultipartFile[] imgFiles) {
	        response.setContentType("text/plain;charset=UTF-8");
	        String url = "";
	       Map<String,Object> obj = new HashMap<String,Object>();
	        try {
	            for (MultipartFile myFile : imgFiles) {
	                Map imgPath = uploadImg(response, request, myFile);// 上传方法
	                if (imgPath.get("error").equals("0")) {
	                    url += imgPath.get("url");
	                }
	            }
	            obj.put("error", 0);// 上传成功
	            if (url.length() > 0) {
	            	obj.put("url", url);
	            } 
	        } catch (Exception e) {
	            e.printStackTrace();
	            obj.put("error", 1);// 上传失败
	            obj.put("url", url);
	        }
	        //map转json
	        JSONObject jsonObject = new JSONObject(obj);
	        String result = jsonObject.toString();
	        return result;
	    }

	    /**
	     * 错误提示
	     * 
	     * @param message
	     * @return
	     */
	    private Map<String, Object> returnErrorMap(String message) {
	        Map<String, Object> map = new HashMap<String, Object>();
	        map.put("error", 1);
	        map.put("message", message);
	        return map;
	    }	 

五、效果图

 

六、插入到编辑框中图片大小如何自适应框呢?打开kindeditor-all.js找到insertimage修改即可:

insertimage : function(url, title, width, height, border, align) {
		title = _undef(title, '');
		border = _undef(border, 0);
		var html = '<img src="' + _escape(url) + '" data-ke-src="' + _escape(url) + '" ';
		/*if (width) {
			html += 'width="' + _escape(width) + '" ';
		}*/
		html += 'width="100%"';
		if (height) {
			html += 'height="' + _escape(height) + '" ';
		}
		if (title) {
			html += 'title="' + _escape(title) + '" ';
		}
		if (align) {
			html += 'align="' + _escape(align) + '" ';
		}
		html += 'alt="' + _escape(title) + '" ';
		html += '/>';
		return this.inserthtml(html);
	},

 

 

 

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
1. 首先,在 `application\extra` 目录下新建一个 `config.php` 文件,添加以下配置: ```php <?php return [ 'upload_path' => '/uploads/', //上传文件保存的路径 'upload_exts' => 'gif,jpg,jpeg,png,bmp', //允许上传的文件类型 ]; ``` 2. 在 `application\index\controller` 目录下新建一个 `Upload.php` 控制器,添加以下代码: ```php <?php namespace app\index\controller; use think\Controller; use think\Request; class Upload extends Controller { public function uploadImage() { $file = request()->file('imgFile'); $info = $file->validate(['ext' => config('upload_exts')])->move(ROOT_PATH . 'public' . config('upload_path')); if ($info) { $image_url = config('upload_path') . $info->getSaveName(); return json(['error' => 0, 'url' => $image_url]); } else { return json(['error' => 1, 'message' => $file->getError()]); } } } ``` 3. 在 `application\index\view` 目录下新建一个 `upload_image.html` 文件,添加以下代码: ```html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>上传图片</title> </head> <body> <form action="<?php echo url('upload/uploadImage'); ?>" enctype="multipart/form-data" method="post"> <input type="file" name="imgFile"> <input type="submit" value="上传"> </form> </body> </html> ``` 4. 修改 `kindeditor` 配置文件 `public\static\kindeditor\config.js`,添加以下代码: ```javascript //上传图片配置 imageUploadJson = '<?php echo url("upload/uploadImage"); ?>'; ``` 5. 在 `public\static\kindeditor\plugins` 目录下新建一个 `image.php` 文件,添加以下代码: ```php <?php //获取上传文件保存的路径 $save_path = $_SERVER['DOCUMENT_ROOT'] . $_POST['save_path']; //获取要上传的文件 $file = $_FILES['imgFile']; //上传文件 if (move_uploaded_file($file['tmp_name'], $save_path . $file['name'])) { $image_url = $_POST['base_url'] . $_POST['save_path'] . $file['name']; //返回上传结果 echo json_encode(['error' => 0, 'url' => $image_url]); } else { echo json_encode(['error' => 1, 'message' => '上传失败']); } ``` 6. 修改 `kindeditor` 的 `php` 上传文件处理程序 `public\static\kindeditor\php\upload_json.php`,添加以下代码: ```php //获取要保存的文件路径和文件名 $save_path = $_SERVER['DOCUMENT_ROOT'] . $_POST['save_path']; $file_name = uniqid() . strrchr($_FILES['imgFile']['name'], '.'); //上传文件 if (move_uploaded_file($_FILES['imgFile']['tmp_name'], $save_path . $file_name)) { $image_url = $_POST['base_url'] . $_POST['save_path'] . $file_name; //返回上传结果 echo json_encode(['error' => 0, 'url' => $image_url]); } else { echo json_encode(['error' => 1, 'message' => '上传失败']); } ``` 7. 在浏览器中访问 `http://localhost/index/upload_image.html`,上传一张图片测试。如果上传成功,会返回图片的 URL 地址。在 `kindeditor` 中也可以正常上传图片了。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

yjm2017

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值