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


富文本編輯的組件有很多,大名鼎鼎的KENDO UI中自然也有,但是默認功能中,只能包含網絡圖片,

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

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

1、先在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

2、在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為按鈕的樣式。

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

JSP代碼:

 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是對文件選擇控件的包裝,為了顯示效果好看些。

uploadImg方法采用了ajaxSubmit方式進行提交,這里需要引用jquery.form.js插件,

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

4、最后在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中插入該地址即可展示圖片


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM