STUDY/PHP

썸머노트 - 반응형 에디터, 썸머노트 파일 업로드

Huwon 2023. 1. 6. 14:23

●반응형 에디터인 썸머노트를 적용하기

https://summernote.org/

https://summernote.org/ 에서 위의 이미지처럼 다운로드 받기

●필요한 파일들을 업로드

  • summernote-bs4.css
  • summernote-bs4.js
  • summernote-ko-KR.js

● 업로드 시킨 파일들을 연결(head)

<link rel="stylesheet" href="<?=STATIC_HTTP?>/css/summernote-bs4.css">
   <script defer src="<?=STATIC_HTTP?>/js/summernote-bs4.js"></script>
   <script defer src="<?=STATIC_HTTP?>/js/summernote-ko-KR.js"></script>

 

  view

<textarea class="bg-mgr d-flex justify-content-center align-items-center"  id="summernote" name="summernote" style="display: none !important;">
</textarea>

에디터가 들어가야 하는 영역에 id와 name값을 준다.

 

  js

$(document).ready(function() {

        $('#summernote').summernote({

            /* 폰트선택 툴바 사용하려면 주석해제 */
            // fontNames: ['Roboto Light', 'Roboto Regular', 'Roboto Bold', 'Apple SD Gothic Neo'],
            // fontNamesIgnoreCheck: ['Apple SD Gothic Neo'],
            tabsize: 2,
            height: 500,
            resize: false,
            lang: "ko-KR",
            disableResizeEditor: true,
            focus: true,
            toolbar: [
      			    // [groupName, [list of button]]
      			    ['fontname', ['fontname']],
      			    ['fontsize', ['fontsize']],
      			    ['style', ['bold', 'italic', 'underline','strikethrough', 'clear']],
      			    ['color', ['forecolor','color']],
      			    ['table', ['table']],
      			    ['para', ['ul', 'ol', 'paragraph']],
      			    ['height', ['height']],
      			    ['insert',['picture','link','video']],
      			    ['view', ['fullscreen', 'help']]
      			  ],
      			fontNames: ['Apple SD Gothic Neo','Arial', 'Arial Black', 'Comic Sans MS', 'Courier New','맑은 고딕','궁서','굴림체','굴림','돋음체','바탕체'],
      			fontSizes: ['8','9','10','11','12','14','16','18','20','22','24','28','30','36','50','72'],
            callbacks: {	//이미지를 첨부하는 부분
                onImageUpload: function (files) {
                    RealTimeImageUpdate(files, this);
                }
            }
        });
        
        var nt_content = `<?php echo $content?>`;
        
        $('#summernote').summernote('code',nt_content);
        $('.note-current-fontname').css('font-family','Apple SD Gothic Neo').text('Apple SD Gothic Neo');
        $('.note-editable').css('font-family','Apple SD Gothic Neo');

        $(".note-group-image-url").remove();    //이미지 추가할 때 Image URL 등록 input 삭제

        $("#submit-btn").click(function(){
            var text = $('#summernote').summernote('code');
        });

        /*
         - 이미지 추가 func
         
        */
        function RealTimeImageUpdate(files, editor) {

            var formData = new FormData();
            var fileArr = Array.prototype.slice.call(files);

            for(var xx=0;xx<files.length;xx++){
                formData.append("file[]", files[xx]);
            }

            $.ajax({
                url : "./summernote.php",
                data: formData,
                cache: false,
                contentType: false,
                processData: false,
                enctype	: 'multipart/form-data',
                type: 'POST',
                success : function(result) {
                    //항상 업로드된 파일의 url이 있어야 한다.
                    if(result === -1){
                        alert('이미지 파일이 아닙니다.');
                        return;
                    }
                    var data = JSON.parse(result);
                    for(x=0;x<data.length;x++){
                        var img = $("<img>").attr({src: data[x], width: "50%"});
                        $(editor).summernote('pasteHTML', "<img src='"+data[x]+"' style='width:50%;' />");
                    }
                }
            });
        }
    });

$content 는 ‘수정’ 일 경우 기존의 데이터를 해당 함수에 넣어서 부른다.

● 이미지 업로드 위한php 파일(www 아래에서 생성할 경우 안의 경로들을 그대로 한다)


$date = date("YmdHis");

/* 서버내의 실제 파일 저장경로 */
$uploadBase = './images/uploads/';

/* src에 찍어줄 경로 */
$uploadUrlBase = '';
$idx = 0;
$result = array();

foreach ($_FILES['file']['name'] as $f => $name) {
    $idx++;
    $name = $_FILES['file']['name'][$f];

    $exploded_file = explode(".", $name);
    $file_extension = array_pop($exploded_file);	//파일 확장자

    $thisName = "nt_content_editor_".$date.$idx.".".$file_extension;

    $uploadFile = $uploadBase.$thisName;

    if(move_uploaded_file($_FILES['file']['tmp_name'][$f], $uploadFile)){
        array_push($result, $uploadUrlBase.$thisName);
    }
}
echo json_encode($result, JSON_UNESCAPED_UNICODE);

exit;

'STUDY > PHP' 카테고리의 다른 글

팝업 오늘 하루 안보기 - 쿠키 사용  (0) 2023.01.06
<fome><input><select><GET><POST>  (0) 2021.05.06
php 자료형 함수  (0) 2021.05.04
php기본 출력함수  (0) 2021.05.03
PHP란?  (0) 2021.05.01