썸머노트 이미지 업로드 방식 변경에 관하여

늘 고생하시는 제작자님 감사합니다.

 

썸머노트 자체 이미지 업로드 기능을 사용했을 경우 base64로 이미지가 업로드 되어 서버에 크게 무리가 가더라구요.

제작자님께서 자체적으로 제작해주신 이미지 업로드 기능도 있지만 썸머노트를 사용할 경우 드래그앤 드랍 기능 때문에 편리해서 일단은 이 부분에 대해 수정을 해보려고 하는데요.

 

구글링을 해보니 썸머노트 자체기능인 콜백함수를 이용하던데...

 

그래서 올려주신 코드 

add_action('wp_head', 'wp_head_2020_03_20');
function wp_head_2020_03_20(){
	?>
	<script>
	jQuery(document).ready(function(){
		var kboard_mod = jQuery('input[name=mod]', '.kboard-form').val();
		if(kboard_mod == 'editor'){
			if(kboard_current.use_tree_category == 'yes'){
				kboard_tree_category_parents();
			}

			if(kboard_current.use_editor == 'snote'){ // summernote
				jQuery('.summernote').each(function(){
					var height = parseInt(jQuery(this).height());
					var placeholder = jQuery(this).attr('placeholder');
					var lang = 'en-US';

					if(kboard_settings.locale == 'ko_KR'){
						lang = 'ko-KR';
					}
					else if(kboard_settings.locale == 'ja'){
						lang = 'ja-JP';
					}

					jQuery(this).summernote({
						toolbar: [
					          ['font', ['bold', 'underline', 'clear']],
					          ['color', ['color']],
					          ['para', ['ul', 'ol']],
					          ['table', ['table']],
					          ['insert', ['link', 'video']],
					          ['view', ['fullscreen', 'codeview']]
					    ],
						lang: lang,
						height: height,
						placeholder: placeholder
					});
				});
			}
		}
	});
	</script>
	<?php
}

 

여기에다가

 

add_action('wp_head', 'wp_head_2020_03_20');
function wp_head_2020_03_20(){
	?>
	<script>
	jQuery(document).ready(function(){
		var kboard_mod = jQuery('input[name=mod]', '.kboard-form').val();
		if(kboard_mod == 'editor'){
			if(kboard_current.use_tree_category == 'yes'){
				kboard_tree_category_parents();
			}

			if(kboard_current.use_editor == 'snote'){ // summernote
				jQuery('.summernote').each(function(){
					var height = parseInt(jQuery(this).height());
					var placeholder = jQuery(this).attr('placeholder');
					var lang = 'en-US';

					if(kboard_settings.locale == 'ko_KR'){
						lang = 'ko-KR';
					}
					else if(kboard_settings.locale == 'ja'){
						lang = 'ja-JP';
					}

					jQuery(this).summernote({
            callbacks: {
                       onImageUpload: function(image) {
                        uploadImage(image[0]);
                       }
               },
						toolbar: [
					          ['font', ['bold', 'underline', 'clear']],
					          ['color', ['color']],
					          ['para', ['ul', 'ol']],
					          ['table', ['table']],
					          ['insert', ['link', 'video']],
					          ['view', ['fullscreen', 'codeview']]
					    ],
						lang: lang,
						height: height,
						placeholder: placeholder
					});

          function uploadImage(image) {
                 var data = new FormData();
                 data.append("image", image);
                 $.ajax({
                     type: "post",
                     cache: false,
                     contentType:false,
                     processData: false,
                     dataType :'jsonp',
                     url: '/cop/bbs/insertSummberNoteFile.do',
                     data: data,
                     success: function(data) { /wp-content/themes/new/img
                         var image = $('<img>').attr('src', '/cmm/fms/getImage.do?atchFileId='+data[0].atchFileId+'&fileSn=0');
                         $('#nttCn').summernote("insertNode", image[0]);
                     },
                     error: function(data) {
                         alert('error : ' +data);
                     }
                 });
             }
          
				});
			}
		}
	});
	</script>
	<?php
}

 

이런 식으로 콜백 함수를 넣고

 

자바 파일에다가 

 

/**
     * 단순 파일 업로드.
     *
     * @param boardVO
     * @param board
     * @param sessionVO
     * @param model
     * @return
     * @throws Exception
     */
    @RequestMapping("/cop/bbs/insertSummberNoteFile.do")
    public void insertSummberNoteFile(final MultipartHttpServletRequest multiRequest, @ModelAttribute("searchVO") BoardVO boardVO, @ModelAttribute("bdMstr") BoardMaster bdMstr,
            @ModelAttribute("board") Board board, BindingResult bindingResult, SessionStatus status, ModelMap model, HttpServletRequest request,HttpServletResponse response) throws Exception {
        LoginVO user = (LoginVO) EgovUserDetailsHelper.getAuthenticatedUser();
        Boolean isAuthenticated = EgovUserDetailsHelper.isAuthenticated();
        JSONArray reportJsonArray = new JSONArray();
        if (isAuthenticated) {
            List<FileVO> result = null;
            String atchFileId = "";
            final Map<String, MultipartFile> files = multiRequest.getFileMap();
            if (!files.isEmpty()) {
                result = fileUtil.parseFileInf(files, "BBS_", 0, "", "");
                atchFileId = fileMngService.insertFileInfs(result);
                JSONObject obj = new JSONObject();
                System.out.println(">>>>> atchFileId : " +atchFileId);
                obj.put("atchFileId", atchFileId);
                reportJsonArray.add(obj);
            }
                
            JSONObject obj = new JSONObject();
            reportJsonArray.add(obj);
                    
            response.setCharacterEncoding("utf-8");
            response.getWriter().println(request.getParameter("callback") + "(" + reportJsonArray+ ")");
            response.getWriter().close();
        }
    }

 

이 코드를 넣으라고 해서 넣었는데 동작이 안되가지구요.. 머리 끙끙 싸메다가 이런 것까지 여쭤보기에는 정말 죄송하지만 도움을 얻고자 합니다..ㅜㅜ

 

혹시 방법이 있을까요..?

 

 

좋은 정보와 인맥을 동시에, 워드프레스 사용자 단톡방 참여하기
좋은 정보와 인맥을 동시에, 워드프레스 사용자 단톡방 참여하기
  • 제작자님 오실 때까지 방법 연구..

     

    jQuery(this).summernote({
    						toolbar: [
    					          ['font', ['bold', 'underline', 'clear']],
    					          ['color', ['color']],
    					          ['para', ['ul', 'ol']],
    					          ['table', ['table']],
    					          ['insert', ['link','picture', 'video']],
    					          ['view', ['fullscreen', 'codeview']]
    					    ],
                  callbacks: {
                    onImageUpload: function(image) {
                      editor = $(this);
                      uploadImageContent(image[0], editor);
    
                      var data = new FormData();
                      data.append('image', image);
                      $.ajax({
                        url: "/wp-content/themes/new/uploadImage.php",
                        cache: false,
                        contentType: false,
                        processData: false,
                        data: data,
                        type: "post",
                        success: function(url) {
                          var image = $('<img>').attr('src', url);
                          $(editor).summernote("insertNode", image[0]);
                        },
                        error: function(data) {
                          console.log(data);
                        }
                      });
    
                    }
                  },
    						lang: lang,
    						height: height,
    						placeholder: placeholder
    					});

     

    + uploading.php 올려서 해보기..

     

    <?php
    
    $return_value = "";
    
      if ($_FILES['image']['name']) {
        if (!$_FILES['image']['error']) {
          $name = md5(rand(100, 200));
          $ext = explode('.', $_FILES['image']['name']);
          $filename = $name . '.' . $ext[1];
          $destination = '/wp-content/themes/new/images' . $filename;
          $location = $_FILES["image"]["tmp_name"];
          move_uploaded_file($location, $destination);
          $return_value = '/wp-content/themes/new/images' . $filename;
        }else{
          $return_value = 'Ooops! Your upload triggered the following error: '.$_FILES['image']['error'];
        }
      }
    
    echo $return_value;
    ?>
    

     

    실패..

  • https://programmer93.tistory.com/31 여기를 참고해보기도 하고..

     

    http://www.areyoucodingenough.com/programming/best-solution-insert-images-content-using-summernote/ 여기를 참고해보기도 하고..

     

    갑갑허네용.. 후..

  • Function.php 안의 코드

    add_action('wp_head', 'wp_head_2020_03_20');
    function wp_head_2020_03_20(){
    	?>
    	<script>
    	jQuery(document).ready(function(){
    		var kboard_mod = jQuery('input[name=mod]', '.kboard-form').val();
    		if(kboard_mod == 'editor'){
    			if(kboard_current.use_tree_category == 'yes'){
    				kboard_tree_category_parents();
    			}
    
    			if(kboard_current.use_editor == 'snote'){ // summernote
    				jQuery('.summernote').each(function(){
    					var height = parseInt(jQuery(this).height());
    					var placeholder = jQuery(this).attr('placeholder');
    					var lang = 'en-US';
    
    					if(kboard_settings.locale == 'ko_KR'){
    						lang = 'ko-KR';
    					}
    					else if(kboard_settings.locale == 'ja'){
    						lang = 'ja-JP';
    					}
    
    					jQuery(this).summernote({
    						toolbar: [
                  ['font', ['bold', 'underline', 'clear']],
                  ['color', ['color']],
                  ['para', ['ul', 'ol']],
                  ['table', ['table']],
                  ['insert', ['link','picture', 'video']],
                  ['view', ['fullscreen', 'codeview']]
                ],
    
                callbacks: {
                onImageUpload:function(files, editor, welEditable){
                    for(var i = files.length - 1;i>=0;i--){
                        sendFile(files[i], this);
                    }
                }
            },
    						lang: lang,
    						height: height,
    						placeholder: placeholder
    					});
    
              function sendFile(file, el, welEditable){
                  var form_data = new FormData();
                  form_data.append('file', file);
                  $.ajax({
                      data:form_data,
                      type:"POST",
                      url:'./editor-upload.php',
                      cache:false,
                      contentType:false,
                      processData:false,
                      success:function(url){
                          $(el).summernote('editor.insertImage', $.trim(url));
                      },
                      error: function(data) {
                          console.log(data);
                      }
                  });
              }
    
    				});
    			}
    		}
    	});
    	</script>
    	<?php
    }

     

    editor-upload.php 안의 코드

    <?php
    if ($_FILES['file']['name']) {
        if (!$_FILES['file']['error']) {
            $temp = explode(".", $_FILES["file"]["name"]);
            $newfilename = round(microtime(true)).'.'.end($temp);
            $destinationFilePath = './wp-content/themes/new/images/'.$newfilename;
            if (!move_uploaded_file($_FILES['file']['tmp_name'], $destinationFilePath)) {
                echo $errorImgFile;
            }
            else{
                echo $destinationFilePath;
            }
        }
        else {
            echo  $message = '파일 에러 발생!: ' . $_FILES['file']['error'];
        }
    }
    ?>
    

     

    실패..

     

     

    이렇게 하니 아예 사진 기능이 URL 빼곤 반응 자체가 없네요..ㅜㅜ

     

    구글링 해보니까 방식 자체는 Kboard 자체 사진 기능이랑 되게 비슷한 거 같은데..

  • 안녕하세요.. 코드를 보고 있는데요.. 

    마지막에 insertNode 하시는 곳의 this 가   실제로 summernote 객체가 아닌 것 같습니다. 

    const self = this; 

    jQuery(this).summernote({  

    형태로 두시고 

    sendFile(files[i], self);

    개별 this 를 넣어주시면 될 것 같아요. 

     

     

  • 안녕하세요~^^

    최신 버전의 KBoard 플러그인에서는

    KBoard 미디어 추가 시 드래그 앤 드롭으로 이미지를 추가하실 수 있습니다.

    썸머노트 에디터 이미지 업로드 관련해서는 저희도 연구를 해봐야 할 듯합니다.

    좋은 방법을 찾게 되면 다시 안내해드리겠습니다.

    고맙습니다.

워드프레스 에러 기술지원 서비스 전문가에게 맡기세요