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

时间:2017-06-22 08:49:39

标签: ajax spring-mvc file-upload tinymce

我正在制作电子商务的内容管理系统,并且会在页面的不同部分显示一个块。这个块可以包含h​​tml和图像,因此我使用TinyMCE来管理块内容。

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

JavaScript取自this theme个答案(我使用了steve.hanson答案),但我改变了一点以适应我的控制器并在设置功能中移动了图像按钮方法。

1 个答案:

答案 0 :(得分:2)

重要的是 - 'files'是ajax和controller中多部分表单变量的名称,请求url是:'$ {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();
    }
}