spring mvc 页面dialog嵌入Kindeditor 实现附件文件上传

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/zhenqian52/article/details/84936762

需求:

页面中弹出dialog页面,并在页面中实现富文本框kindeditor并提供附件上传功能。

首先页面引入相关js和css文件

<link rel="stylesheet" href="<%=request.getContextPath() %>/kindeditor/themes/default/default.css" />
<link rel="stylesheet" href="<%=request.getContextPath() %>/kindeditor/plugins/code/prettify.css" />
 <script charset="utf-8" src="<%=request.getContextPath() %>/kindeditor/kindeditor-all.js"></script>
 <script charset="utf-8" src="<%=request.getContextPath() %>/kindeditor/lang/zh-CN.js"></script>
<script charset="utf-8" src="<%=request.getContextPath() %>/kindeditor/plugins/code/prettify.js"></script>

js内容

  <script type="text/javascript" >
	    
        KindEditor.ready(function(K) {
            window.editor = K.create('#editor_id', {
                uploadJson: '<%=request.getContextPath()%>/XXXAdmin/uploadfj.htm',
                fileManagerJson: '<%=request.getContextPath() %>/kindeditor/jsp/file_manager_json.jsp',
                allowFileManager: true,
                afterCreate: function() {
                    var self = this;
                    K.ctrl(document, 13,
                    function() {
                        self.sync();
                        document.forms['#form'].submit();
                    });
                    K.ctrl(self.edit.doc, 13,
                    function() {
                        self.sync();
                        document.forms['#form'].submit();
                    });
                }
            });
        });
    function append() {   	    

	   	            
	 $("#addxxxlDialog").dialog({
	   	                title: '新增文章',
	   	                width: 1100,
	   	                height: 500,
	   	                left: 150,
	   	                top: 20,
	   	                bottom: 50,
	   	                modal: true,
	   	                resizable: true,
	   	                position: 'center',
	   	                buttons: [{
	   	                    text: '保存',
	   	                    handler: function() {
	   	                        var id = $("#id").val();
	   	                       
	   	                        var content = editor.html();
	   	                        $.post("<%=request.getContextPath()%>/xxxxAdmin/savexxxxDialog.htm", {
	   	                            "id": id,
	   	                     	    "content": content,
	   	                            
	   	                        },
	   	                        function(data) {
	   	                            if (data !== 0 && data !== null) {
	   	                                $.messager.alert("提示", "增加文章成功!");
	   	                            } else {
	   	                                $.messager.alert("提示", "增加文章失败!");
	   	                                return false;
	   	                            }
	   	                        }).complete(function() {
	   	                            $("#form").form('clear');
	   	                            editor.html("");
	   	                            $("#addArticalDialog").dialog("close");
	   	                            //刷新页面
	   	                            url = "<%=request.getContextPath() %>/XXXAdmin/XXXForGrid.htm";
	                        $('#dg').datagrid('options').queryParams.dNum = dNum;
                                $('#dg').datagrid('options').queryParams.aId = aCId;
	   	                            $('#dg').datagrid('reload', url);
	   	                        });

	   	                    }
	   	                },
	   	                {
	   	                    text: '取消',
	   	                    handler: function() {
	   	                        $("#addxxxxDialog").dialog("close");
	   	                    }
	   	                }]

	   	            });
	   	            $("#form").form('clear');
	   	            editor.html("");
	   	            $("#addxxxxDialog").dialog("open");
	   	        } else {
	   	            $.messager.alert("提示", "当前层级不允许新增内容!");
	   	        }
	   	    } else {
	   	        $.messager.alert("提示", "当前层级不允许新增内容!");
	   	    }
	   	}
</script>

然后是html页面

<div id="addArticalDialog"  class="easyui-dialog" closed="true">
	<form action=" " method="post" name="form"  id="form" enctype="multipart/form-data">
              <table width="90%" border="0" cellpadding="0" cellspacing="1" class="list_border_bg">
              
                <tr>
                  <td height="28" align="right" class="list_left_title">文章标题:</td>
                  <td height="28" class="list_cell_bg">			 
				        <input type="text" name="title" id="title" value="${requestScope.ar.title }" size="40" />
				         </td>
                </tr>
                <tr>
                  <td height="28" colspan="4" align="left" class="list_left_title">
				   <div align="center">
					<textarea id="editor_id" name="editor_id" style="width:1024px;height:500px;">
					</textarea>
                  </div>
                  </td>
                </tr>
                <tr>
                 	<td>
		             <input type="hidden" value="${requestScope.ar.id }" name="id" id="id"/>
                   </td>
                </tr>
  </table>
</form>
</div>

controller部分

@RequestMapping(value = "/uploadfj")
	  public String uploadfj( HttpServletRequest request,HttpServletResponse response, ModelMap modelmap) throws Exception {
		PrintWriter writer = response.getWriter();
		DESPlus des = new DESPlus();
		try {
			// 文件保存路径
			String saveUrl = "";
			// 定义允许上传的文件扩展名
			HashMap<String, String> extMap = new HashMap<String, String>();
			extMap.put("image", "gif,jpg,jpeg,png,bmp");
			extMap.put("flash", "swf,flv");
			extMap.put("media", "swf,flv,mp3,wav,wma,wmv,mid,avi,mpg,asf,rm,rmvb");
			extMap.put("file", "doc,docx,xls,xlsx,ppt,htm,html,txt,zip,rar,gz,bz2");
			// 最大文件大小
			long maxSize = 1024*1024*2;
			response.setContentType("text/html; charset=UTF-8");
			if (!ServletFileUpload.isMultipartContent(request)) {
				writer.println(getError("请选择文件!!!!。"));
				return null;
			}
			String dirName = request.getParameter("dir");
			if (dirName == null) {
				dirName = "image";
			}
			if (!extMap.containsKey(dirName)) {
				writer.println(getError("目录名不正确。"));
				return null;
			}
			//读取文件
			MultipartHttpServletRequest mRequest = (MultipartHttpServletRequest) request;
			Map<String, MultipartFile> fileMap = mRequest.getFileMap();
			//文件名
			String fileName = null;
			for (Iterator<Map.Entry<String, MultipartFile>> it = fileMap.entrySet().iterator(); it.hasNext();) {
				Map.Entry<String, MultipartFile> entry = it.next();
				MultipartFile mFile = entry.getValue();
				//原始名称
				fileName = mFile.getOriginalFilename();
				// 检查上传文件大小
				if (mFile.getSize() > maxSize) {
					writer.println(getError("上传文件大小超过限制。"));
					return null;
				}
				//截取文件类型
				String fileExt = fileName.substring(fileName.lastIndexOf(".")+1);
				if (!Arrays.<String> asList(extMap.get(dirName).split(",")).contains(fileExt)) {
					writer.println(getError("上传文件扩展名是不允许的扩展名。n只允许" + extMap.get(dirName) + "格式。"));
					return null;
				}
				InputStream is = mFile.getInputStream();
				int articlefileid = (int)this.articleClassService.getAutoArticleFileId();//获取当前文章的ID用来做Key  没有就用个自增的
				String fileKey = articlefileid;//文件key
				this.articleClassService.upFileByOss(PHOTOBUCKETNAME, fileKey, is,fileName);//上传到OSS 并设置下载名称为fileName
				String rswbBucket = AliyunOss.getRswbBucket();
				String endPonint = AliyunOss.getEndpoint().replace("http://", "");
				saveUrl ="http://"+rswbBucket+"."+endPonint+"/"+articlefileid;
				//将相关信息存储到article_file表中
				JSONObject obj = new JSONObject();
				obj.put("error", 0);
				obj.put("url", saveUrl);
				obj.put("title", fileName);//  修改js文件进行,设置自动设置title  ,文件说明。
				writer.println(obj.toString());
			}
		}
		catch (Exception ex) {
			writer.println(getError(ex.toString()));
			return null;
		}
		return null;
	}
private String getError(String message) {
		JSONObject obj = new JSONObject();
		obj.put("error", 1);
		obj.put("message", message);
		return obj.toString();
	}

其它就不贴了 警醒自己就够了

弄清楚:在上传的时候oss需要一个永不重复的Key,最好的就是自增的ID,如果没有就自己写一个seqence,文件上传成功之后,需要返回url,这个url会以超链接的方式展示到文章内容中,如果想设置这个url的title,需要修改相应的js文件,修改之后在后台,将title用put 放到返回得json中,

展开阅读全文

没有更多推荐了,返回首页