2017-06-22 95 views
1

我正在製作電子商務的內容管理系統,並在頁面的不同部分顯示一個塊。該塊可以包含h​​tml和圖像,所以我使用TinyMCE來管理塊內容。如何從TinyMCE編輯器上載Spring MVC中的圖像

我沒有找到完整的解決方案 - 只有單獨的問題關於TineMCE或加載圖像控制器,所以我想與你分享我的經驗 - 爲TinyMCE初始化和後端控制器完成JavaScript,保存圖像。

JavaScript是從this theme答案(我用steve.hanson答案),但我改變了一下,以適應我的控制器和移動設置功能內的圖像按鈕方法。

回答

2

重要的東西─ '文件' 是在Ajax和控制器多表單變量的名稱,請求URL是: '$ {} pageContext.request.contextPath/A /圖片'

的JavaScript TinyMCE的初始化和Ajax請求處理圖像:

<script src="https://cloud.tinymce.com/stable/tinymce.min.js"></script> 
<script> 
tinymce.init({  
     selector: 'textarea', // change this value according to your HTML 
     auto_focus: 'element1', 
     toolbar: 'undo redo | imageupload', 
     setup: function(editor) { 

       // create input and insert in the DOM 
       var inp = $('<input id="tinymce-uploader" type="file" name="pic" accept="image/*" style="display:none">'); 
       $(editor.getElement()).parent().append(inp); 

       // add the image upload button to the editor toolbar 
       editor.addButton('imageupload', { 
       text: 'Add image', 
       icon: 'image', 
       onclick: function(e) { // when toolbar button is clicked, open file select modal 
        inp.trigger('click'); 
       } 
       }); 

       // when a file is selected, upload it to the server 
       inp.on("change", function(e){ 
       uploadFile($(this), editor); 
       }); 


      function uploadFile(inp, editor) { 
       var input = inp.get(0); 
       var data = new FormData(); 
       data.append('files', input.files[0]); 

       $.ajax({ 
       url: '${pageContext.request.contextPath}/a/images', 
       type: 'POST', 
       data: data, 
       enctype: 'multipart/form-data', 
       dataType : 'json', 
       processData: false, // Don't process the files 
       contentType: false, // Set content type to false as jQuery will tell the server its a query string request 
       success: function(data, textStatus, jqXHR) { 
        editor.insertContent('<img class="content-img" src="${pageContext.request.contextPath}' + data.location + '" data-mce-src="${pageContext.request.contextPath}' + data.location + '" />'); 
       }, 
       error: function(jqXHR, textStatus, errorThrown) { 
        if(jqXHR.responseText) { 
        errors = JSON.parse(jqXHR.responseText).errors 
        alert('Error uploading image: ' + errors.join(", ") + '. Make sure the file is an image and has extension jpg/jpeg/png.'); 
        } 
       } 
       }); 
      } 
     } 
    }); 


</script> 

這裏是我的Spring MVC控制器和方法來保存文件:

@RequestMapping(value = "https://stackoverflow.com/a/images", method = RequestMethod.POST) 
@ResponseBody 
public String handleTinyMCEUpload(@RequestParam("files") MultipartFile files[]) { 
    System.out.println("uploading______________________________________MultipartFile " + files.length); 
    String filePath = "/resources/uploads/tinyMCE/" + files[0].getOriginalFilename(); 
    String result = uploadFilesFromTinyMCE("tinyMCE", files, false); 
    System.out.println(result); 
    return "{\"location\":\"" + filePath + "\"}"; 

} 

private String uploadFilesFromTinyMCE(String prefix, MultipartFile files[], boolean isMain) { 
    System.out.println("uploading______________________________________" + prefix); 
    try { 
     String folder = context.getRealPath("/") + "/resources/uploads/" + prefix; 
     StringBuffer result = new StringBuffer(); 
     byte[] bytes = null; 
     result.append("Uploading of File(s) "); 

     for (int i = 0; i < files.length; i++) { 
      if (!files[i].isEmpty()) { 

       try { 
        boolean created = false; 

        try { 
         File theDir = new File(folder); 
         theDir.mkdir(); 
         created = true; 
        } catch (SecurityException se) { 
         se.printStackTrace(); 
        } 
        if (created) { 
         System.out.println("DIR created"); 
        } 
        String path = ""; 
        path = folder + files[i].getOriginalFilename(); 
        File destination = new File(path); 
        System.out.println("--> " + destination); 
        files[i].transferTo(destination); 
        result.append(files[i].getOriginalFilename() + " Succsess. "); 
       } catch (Exception e) { 
        throw new RuntimeException("Product Image saving failed", e); 
       } 

      } else 
       result.append(files[i].getOriginalFilename() + " Failed. "); 

     } 

     return result.toString(); 

    } catch (Exception e) { 
     return "Error Occured while uploading files." + " => " + e.getMessage(); 
    } 
}