kendo ui 富文本編輯控件 Editor 實現本地上傳圖片,並顯示

富文本編輯的組件有不少,大名鼎鼎的KENDO UI中天然也有,可是默認功能中,只能包含網絡圖片,html

而若是要實現本地上傳圖片,KENDO UI也提供了相應的功能,但必須實現KENDO規定的多個接口,jquery

並且功能過於豐富,有時項目並用不到,因此我想利用自定義按鈕來實現,下面就是實現過程:ajax

一、先在JSP中定義textarea標籤,做爲富文本編輯框的佔位。服務器

1 <div class="form-group">
2                     <label class="col-xs-2 control-label">項目簡述:</label>
3                     <div class="col-xs-8">
4                         <textarea id="project-desc" type="text" class="form-control" maxlength="10000"></textarea>
5                     </div>
6                 </div>
View Code

二、在JS腳本中定義其爲KendoEditor,並設置其默認按鈕,及自定義按鈕。網絡

 1     $("#project-desc").kendoEditor({
 2           tools: [
 3                       "formatting",
 4                       "bold", "italic", "underline",
 5                       "justifyLeft", "justifyCenter", "justifyRight",
 6                       "insertUnorderedList", "insertOrderedList", "indent", 
 7                       "createTable",
 8                       {
 9                           name: "image",
10                           tooltip: "Insert image",
11                           template: "<button type='button' class='k-button' onclick='uploadimg();'><span class='glyphicon glyphicon-picture' aria-hidden='true'></button>",
12                       }
13                  ],
14                 
15                 keydown: function(e) {
16                     $(".k-editable-area").tooltip('destroy');
17                 }
18     });
View Code

name爲標籤的名字,tooltip爲懸停的提示,template爲按鈕的樣式。session

三、uploadimg()方法是打開文件上傳選擇窗口,這裏我使用的是kendoWindow。app

JSP代碼:dom

 1  <div id="upload-img-win">
 2      <div class="container-fluid">
 3            <form id="editorUploadImg" action="${ctx }/Detail/uploadImg"  enctype='multipart/form-data'>
 4                <input id="srcEditor" type="hidden"/>
 5                <div class="form-group  ld-bottom" id="ImgUploadGroup">
 6                    <label class="col-xs-2 control-label">圖片上傳:</label>
 7                    <div class="col-xs-8">
 8                        <button id="uploadImg-btn" type="button" class="btn btn-primary" onclick="openImgSelectFile();">選擇文件</button>
 9                        <label id="uploadImgFileName" class="control-label"></label>
10                        <input id="uploadImg" name="uploadImg" type="file" class="hidden" onchange="seletedImgFile();"/>
11                    </div>
12                </div> 
13                <div class="row ld-top ld-bottom">
14                    <div class="col-xs-10">
15                        <div class="pull-right">
16                            <button id="doc-save-btn" type="button" class="btn btn-primary" onclick="uploadImgWinObj.save()">保存</button>
17                            <button id="doc-cancel-btn" type="button" class="btn btn-default" onclick="uploadImgWinObj.close()">關閉</button>
18                        </div>
19                    </div>
20                </div>
21            </form>   
22        </div> 
23 </div>
View Code

js代碼:異步

 1 var uploadImgWinObj = null;
 2 //上傳圖片窗口
 3 function uploadImgWin() {
 4     var me = this;
 5 
 6     this.winEl = $("#upload-img-win");
 7     this.winEl.kendoWindow({
 8         draggable   : true,
 9         width       : "650px",
10         modal       : true,
11         pinned      : false,
12         title       : "選擇圖片",
13         visible     : false,
14         animation   : false,
15         resizable   : false,
16         actions     : ["Close"]
17     });
18 
19     this.kObj = this.winEl.data("kendoWindow")
20 
21     this.open = function(srcEditor) {    
22         clearInput("#upload-img-win");
23         $("#uploadImgFileName").html("");
24         $("#uploadImg").val("");
25         $("#srcEditor").val(srcEditor);
26         this.kObj.center();
27         this.kObj.open();
28     }
29 
30     this.close = function() {
31         this.kObj.close();
32     }
33 
34     this.save = uploadImg;
35 }
36 
37 //上傳圖片
38 function uploadImg(){
39     if($("#uploadImg").val()==""){
40         markError("#uploadImg","沒有選擇任何文件!","#editorUploadImg")
41         return;
42     }
43     
44      $("#editorUploadImg").ajaxSubmit({
45          type: "post",
46          success: function (data) {
47              if(data!="-99"){
48 //                 bootbox.alert("操做成功!");
49                  var srcEditor = $("#srcEditor").val();
50                  var editor = $(srcEditor).data("kendoEditor");
51                  editor.exec("insertHTML", { value: "<img src='"+ ctx + "/" + data +"' >"});
52                  uploadImgWinObj.close();
53              }else{
54                  uploadImgWinObj.close();
55                   bootbox.alert("操做失敗!");                                
56              }
57          },
58          error: function(e){
59              bootbox.alert("操做失敗!");
60              uploadImgWinObj.close();
61          }
62      });    
63 }
64 
65 //選擇圖片
66 function openImgSelectFile(){
67     $("#uploadImg").click();
68 }
69 
70 //選中圖片後,顯示圖片名稱
71 function seletedImgFile(){
72     $("#uploadImgFileName").html($("#uploadImg").val());
73 }
74 
75 function uploadimg(){
76     uploadImgWinObj.open("#project-desc");
77 }
78 
79 $(document).ready(function() {
80     uploadImgWinObj = new uploadImgWin();  
81 }
82   
View Code

openImgSelectFile和seletedImgFile是對文件選擇控件的包裝,爲了顯示效果好看些。ide

uploadImg方法採用了ajaxSubmit方式進行提交,這裏須要引用jquery.form.js插件,

該插件可使用AJAX異步方式上傳文件,http://plugins.jquery.com/form/ 這裏能夠下載。

四、最後在Controller裏實現保存上傳圖片功能。

 1 /**
 2      * 上傳圖片
 3      */
 4     @RequestMapping(value="/uploadImg")
 5     @ResponseBody
 6     public String uploadImg(HttpSession session,HttpServletRequest request,HttpServletResponse response,
 7             @RequestParam(value = "uploadImg", required = false) MultipartFile file) {
 8         try {
 9 
10             User loginUser = (User) session.getAttribute("loginUser");
11             
12             // 得到上傳文件的格式
13             String fileName = "";
14             String path = "";
15             String url = "";
16             //無文件則不作文檔保存動做
17             if(file!=null && !"".equals(file.getOriginalFilename()))  {
18                 fileName = file.getOriginalFilename();
19                 String format = fileName.substring(fileName.lastIndexOf("."));
20                 
21                 path = request.getSession().getServletContext().getRealPath("");
22 
23                 //使用UUID命名,防止文件重名
24                 UUID uuid = UUID.randomUUID();
25                 String newFileName = uuid.toString()+format;
26                 url = "resources/upload/"+loginUser.getUserId()+"/img/"+ newFileName;// 文件名
27         
28                 path = path + File.separator + "resources" + File.separator + "upload"+ File.separator+loginUser.getUserId()+ File.separator + "img";
29                 File diagramDirFile = new File(path);
30                 if (!diagramDirFile.exists()) {
31                     //若是文件夾不存在,則建立它
32                     diagramDirFile.mkdirs();
33                 }
34                 path = path + File.separator + newFileName;
35                 //保存上傳文件
36                 FileCopyUtils.copy(file.getBytes(), new FileOutputStream(path));
37                     
38             }        
39             
40             return url;
41             
42         } catch (IOException e) {
43             // TODO Auto-generated catch block
44             e.printStackTrace();
45             return "-99";
46         }
47         
48         
49     }
View Code

服務器回傳上傳圖片的URL,在Editor中插入該地址便可展現圖片

相關文章
相關標籤/搜索