如何从TinyMCE编辑器在Spring MVC中上传图像



我正在为电子商务制作一个内容管理系统,并有一个块,这些块将显示在页面的不同部分。这些块可以包含html和图像,所以我使用TinyMCE的<textarea>来管理块内容。

我在任何地方都没有找到完整的解决方案 - 只有关于TinyMCE或加载图像控制器的单独问题,所以我想与您分享我的经验 - 用于TinyMCE初始化和后端控制器的完整JavaScript,可以保存图像。

JavaScript 取自这个主题答案(我使用了 steve.hanson 答案(,但我稍微改变了它以适应我的控制器并在设置函数中移动了图像按钮方法。

重要的事情 - 'files' 是 ajax 和控制器中多部分表单变量的名称,请求网址是: '${pageContext.request.contextPath}/a/images'

TinyMCE 的 JavaScript 初始化和 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 = "/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();
    }
}

最新更新