본문 바로가기
Languages/HTML & CSS & JS

Tinymce editor 이미지 업로드 & 삽입하기

by 달팽이 "@... 2022. 2. 20.

 많은 레퍼런스들을 참고하여 고민하며 구현한 코드지만 저 스스로도 취업준비생인 초보 개발자이기 때문에 코드 상의 문제 혹은 더 바람직한 우수사례들이 있을 수 있습니다.  코드 작성 시 참고 정도로 활용해주시고 문제나 개선 가능한 부분 발견 시 공유해주신다면 감사하겠습니다.

저는 현재 Quora라는 미국의 질문/답변 소셜 웹사이트를 벤치마킹하여 프로젝트를 진행중에 있습니다

질문, 답변 작성 시 사진을 업로드하는 동시에 Editor 내부에 사진을 삽입해주는 기능이 필요해 tinymce와 jquery를 이용하여 구현 했습니다

 

작업 흐름은 대략 아래와 같습니다

이미지 업로드 버튼 클릭 -> input 태그 작동 -> input 태그에 이미지 추가 시 추가된 이미지 읽어오기 -> 읽어오기 성공 시 에디터에 이미지 삽입

 

코드를 살펴보겠습니다

JQUERY, TINYMCE 추가

<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="/js/tinymce/tinymce.min.js"></script>

(저의 경우는 tinymce를 self hosting으로 이용하고 있습니다 cdn도 사용 가능합니다)

 

HTML

<form action="/board/create" method="POST" enctype="multipart/form-data">
    
    <%--    Editor로 사용할 태그    --%>
    <textarea name="content" id="content" rows="10" cols="30"></textarea>
        
    <%--      이미지 업로드 input 태그(숨김)      --%>
    <input type="file" multiple="multiple" name="image" id="image" style="display: none;" accept="image/*">

</form>

간단한 html form 태그 입니다

에디터로 사용할 textarea 태그와 이미지 업로드 버튼 동작 시 작동시킬 input 태그 입니다

 

TINYMCE 초기화


        // text editor 초기화
        tinymce.init({
            selector: "#content",
            menubar:false,
            statusbar: false,
            toolbar: "custom_image", // 커스텀 버튼 이름

            // 셋업 시 콜백함수
            setup: function(editor) {

                // 커스텀 버튼 생성 (tinymce 5 버전, 첫번째 인자는 toolbar에 추가할 때 사용되는 버튼의 이름)
                editor.ui.registry.addButton('custom_image', {
                    title: 'Insert Image',
                    icon: 'image',

                    // 버튼 동작 시
                    onAction: triggerTag // input 태그 작동 함수
                })
            }}
        )

 1. selector에 text editor로 사용할 태그를 선택한다

2. 이미지 업로드 버튼이 필요하므로 setup 시 콜백함수를 통해 버튼을 추가한다

3. 이미지 업로드 버튼 작동 시 콜백함수로 triggerTag 전달

 

triggerTag


const triggerTag = function () {

    // 이미지 업로드용 input 태그
    const image = $("#image")

    // input 태그 클릭 작동
    image.trigger("click")

    image.on('change', readImage)
}

1. 이미지 업로드 버튼 작동 시 input 태그 동작

2. input 태그 변경 시 콜백함수로 readImage 전달

 

readImage


const readImage = function () {

    // input 태그에 선택된 파일 가져오기
    const file = this.files[0]

    // fileReader 객체 생성
    const reader = new FileReader()

    // fileReader로 file의 url 읽어오기
    reader.readAsDataURL(file)

    // 읽어오기 동작 성공 시 실행
    reader.addEventListener("load", insertImg)

}

1. input 태그에 선택된 파일 url 읽어오기

2. 읽어오기 성공 시 콜백함수로 insertImg 전달

 

insertImg

const insertImg = function (e) {

    // 읽어온 이미지 결과
    const image = e.target.result

    // 읽어온 이미지를 에디터 Content에 img 태그로 추가
    tinymce.activeEditor.insertContent('<img alt="photo" src="' + image + '" style="width: 800px; height: 500px;"/>')

}

 1. 읽어오기 성공한 이미지를 img 태그의 src 속성에 넣어 editor content로 삽입

 

실행 결과 input 태그에서 업로드 이미지의 선택과 함께 에디터에 삽입까지 잘 처리되었습니다

 

 

'Languages > HTML & CSS & JS' 카테고리의 다른 글

AJAX를 이용한 REST 방식의 파일 업로드  (0) 2022.02.22