몰빼미
DON'T PANIC
몰빼미
  • 분류 전체보기
    • 잡담
    • JAVA
    • Oracle
    • Spring
    • Javascript
    • Vue
    • jQuery
    • CSS
    • error

블로그 메뉴

  • 홈
  • 태그
  • 방명록

인기 글

태그

  • 프로젝트
  • 분석함수
  • SUMMERNOTE
  • 백준
  • 스프링부트
  • 오라클

최근 댓글

최근 글

hELLO · Designed By 정상우.
몰빼미

DON'T PANIC

[Springboot] summernote 프로젝트에 이식하기
Spring

[Springboot] summernote 프로젝트에 이식하기

2022. 10. 1. 00:40

summernote

 

프로젝트에 들어가는 게시판 CRUD작업 중

textarea의 아무것도없는 빈칸이 싫증이 났다..

글작성 에디터 api를 기웃거리는데 네이버는 이미 끝났다고하고..

summernote가 제일 디자인도 깔끔하고해서 이식해보려고한다

 

먼저 홈페이지로 가서

 

https://summernote.org/

 

Summernote - Super Simple WYSIWYG editor

Super Simple WYSIWYG Editor on Bootstrap Summernote is a JavaScript library that helps you create WYSIWYG editors online.

summernote.org

 

Getting started -> Download compiled

알집 다운로드 후 css, js, lang폴더 에서 ko만 , font폴더는 몽땅 프로젝트 안에 넣어줌

 

위 사진처럼 넣었음

 

write.jsp폼

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
<head>
<link href="${pageContext.request.contextPath}/resources/css/Summernote/summernote-lite.css" type="text/css" rel="stylesheet">
</head>
<body>
 
 
      <b>내용</b>
      <textarea id="summernote"></textarea>
    
     
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>
<script src="${pageContext.request.contextPath}/resources/js/Summernote/summernote-lite.js"></script>
<script src="${pageContext.request.contextPath}/resources/js/Summernote/lang/summernote-ko-KR.js"></script>
 
</body>
Colored by Color Scripter
cs

아래에 제이쿼리랑 부트스트랩(필수), 위에서 갖고온 summernote css, js들을 위와같이 연결해준다.

 

<script>문

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
$(function(){
        //썸머노트 설정
        $('#summernote').summernote({
              height: 300,                 
              minHeight: null,            
              maxHeight: null,             
              focus: true,                  
              lang: "ko-KR",                
              placeholder: '내용을 입력해주세요',
              callbacks: {
                    onImageUpload: function(files, editor, welEditable) {
                        for(var i = files.length -1; i>=0; i--) {
                            sendFile(files[i], this);
                        }
                    }
                }
 
        });
    
});
 
 
//썸머노트 이미지 파일 업로드
function sendFile(file, editor) {
    data = new FormData();
    data.append("file", file);
    $.ajax({
        data : data,
        type : "POST",
        url : "SummernoteImage",
        contentType : false,
        enctype : 'multipart/form-data',
        processData : false,
        success : function(data) {
            $(editor).summernote('insertImage', data.url);
            console.log(data.url);
        }
    });
}
Colored by Color Scripter
cs

 

summernote 기본설정과 콜백함수로 이미지 다중 업로드를 할 수 있는 script문이다.

 

summernote는 기본 이미지 저장방식이 base64 image여서 소스값이 무쟈게 길다(그냥 넣으면 DB가 힘들어함)

 

ajax로 프로젝트 외부에 이미지를 저장하고 그 간결해진 주소값으로 DB에 저장할 예정이다.

 

Controller.java

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
//썸머노트 이미지 업로드
        @PostMapping(value="/uploadSummernoteImageFile", produces = "application/json")
        @ResponseBody
        public JsonObject SummernoteImage(@RequestParam("file") MultipartFile multipartFile) {
            
            JsonObject jsonObject = new JsonObject();
            
            String fileRoot = "C:\\image\\";    //저장될 외부 파일 경로
            String originalFileName = multipartFile.getOriginalFilename();    //오리지날 파일명
            String extension = originalFileName.substring(originalFileName.lastIndexOf("."));    //파일 확장자
            System.out.println(originalFileName);
            String savedFileName = UUID.randomUUID() + extension;    //저장될 파일 명
            
            File targetFile = new File(fileRoot + savedFileName);    
            
            try {
                InputStream fileStream = multipartFile.getInputStream();
                FileUtils.copyInputStreamToFile(fileStream, targetFile);    //파일 저장
                jsonObject.addProperty("url", "/프로젝트명/summernoteImage/"+savedFileName);
                jsonObject.addProperty("responseCode", "success");
            } catch (IOException e) {
                FileUtils.deleteQuietly(targetFile);    //저장된 파일 삭제
                jsonObject.addProperty("responseCode", "error");
                e.printStackTrace();
            }
            System.out.println(jsonObject);
            
            return jsonObject;
        }
Colored by Color Scripter
cs

base64의 엄청난 소스를 UUID를 이용해 보다 간단한 랜덤값으로 변환해서 저장한다.

 

 

※ 참고로 저기서 엄청나게 해맸던게

url로 보내는 "/프로젝트명/summernoteImage/"+saveFileName 이부분이였는데

계속 post로 잘 보냈고 success까지 떴는데 계속 get 404 에러가 뜨면서 폼에 사진이 안나타나는거

알고보니 /프로젝트명/ 이 빠져있었음..  알아내기까지 엄청난 삽질의 시간이 존재했다.

앞으로 꼭 제발 ★★★경로★★★를 잘 확인하자

 

'Spring' 카테고리의 다른 글

스프링부트 시작하기 in Eclipse  (0) 2022.09.13
    'Spring' 카테고리의 다른 글
    • 스프링부트 시작하기 in Eclipse
    몰빼미
    몰빼미
    침착한 코딩일지

    티스토리툴바