ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • 네이버 스마트 에디터 연동 + SPRING MVC
    Web (Spring ) 2016. 8. 18. 23:56

    네이버 스마트 에디터 다운로드


    http://dev.naver.com/projects/smarteditor/download



    1
    <mvc:resources mapping="/**" location="/webapp/" />



    위의 코드를 자신의 servelet에 넣어준다.

    다운로드가 완료되었다면 압축해제한 파일을 자신의 webapp root에 놓는다.

    모든 리소스(자원들은) webapp에서 끌어온다는 것.

    위와 같은 구조이다. 이어서 계속

    1
    2
    <script type="text/javascript" src="//code.jquery.com/jquery-1.11.0.min.js"></script>
    <script type="text/javascript" src="/smarteditor/js/HuskyEZCreator.js" charset="utf-8"></script>


    에디터를 넣고자 하는 view단에 다음과 같이 스크립트 선언


    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
    $(function(){
        //전역변수선언
        var editor_object = [];
         
        nhn.husky.EZCreator.createInIFrame({
            oAppRef: editor_object,
            elPlaceHolder: "smarteditor",
            sSkinURI: "/naver_editor/SmartEditor2Skin.html"
            htParams : {
                // 툴바 사용 여부 (true:사용/ false:사용하지 않음)
                bUseToolbar : true,             
                // 입력창 크기 조절바 사용 여부 (true:사용/ false:사용하지 않음)
                bUseVerticalResizer : true,     
                // 모드 탭(Editor | HTML | TEXT) 사용 여부 (true:사용/ false:사용하지 않음)
                bUseModeChanger : true
            }
        });
         
        //전송버튼 클릭이벤트
        $("#savebutton").click(function(){
            //id가 smarteditor인 textarea에 에디터에서 대입
            editor_object.getById["smarteditor"].exec("UPDATE_CONTENTS_FIELD", []);
             
            // 이부분에 에디터 validation 검증
             
            //폼 submit
            $("#frm").submit();
        })
    })



    8번 라인 자신의 웹루트(webapp) 

    [필자는 naver_editor 위에 첨부된 이미지 참조]

    20번 라인 submit button id

    27번 라인 form id


    naver_editor\sample\photo_uploader\photo_uploader.html


    1
    <form id="editor_upimage" name="editor_upimage" action="FileUploader.php" method="post" enctype="multipart/form-data" onSubmit="return false;">


    1
    <form id="editor_upimage" name="editor_upimage" method="post" enctype="multipart/form-data" onSubmit="return false;">



    우리는 MVC모델 구조이기 때문에 PHP ACTION은 필요가 없으므로 삭제한다.


    naver_editor\sample\photo_uploader\attach_photo.js


    479번라인 callFileUploader() 함수를 보게 되면


    1
    2
    3
    sUrl  : location.href.replace(/\/[^\/]*$/''+ '/file_uploader.php',  //샘플 URL입니다.
    sCallback : location.href.replace(/\/[^\/]*$/''+ '/callback.html',  //업로드 이후에 iframe이 redirect될 콜백페이지의 주소


    1번라인 본인 파일업로드 컨트롤러

    2번라인은 콜백 Url

    수정


    1
    2
    sUrl  : '/common/photoUpload.do'//변경 URL입니다.
    sCallback : '/naver_editor/sample/photo_uploader/callback.html'//업로드 이후에 iframe이 redirect될 콜백페이지의 주소



    이어서 336번 라인 html5Upload() 함수를 보게되면


    마찬가지로 자신의 다중파일업로드 경로로 수정


    1
    sUploadURL= 'html5upload.php';     //다중파일업로드 URL



    1
    sUploadURL= '/common/multiplePhotoUpload.do';     //다중파일업로드 URL



    위에서 수정한 서버단을 이제 만들어보자



    PhotoVo.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
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    package kr.co.endu.common.common.util;
     
    import org.springframework.web.multipart.MultipartFile;
     
    /**
      * @FileName : PhotoVo.java
      * @Project : hb
      * @Date : 2016. 5. 27. 
      * @author : bin
      * @update :
      * @description : 네이버 스마트 에디터 첨부파일 VO
      */
     
    public class PhotoVo {
        //photo_uploader.html페이지의 form태그내에 존재하는 file 태그의 name명과 일치시켜줌
        private MultipartFile Filedata;
        //callback URL
        private String callback;
        //콜백함수??
        private String callback_func;
     
        public MultipartFile getFiledata() {
            return Filedata;
        }
     
        public void setFiledata(MultipartFile filedata) {
            Filedata = filedata;
        }
     
        public String getCallback() {
            return callback;
        }
     
        public void setCallback(String callback) {
            this.callback = callback;
        }
     
        public String getCallback_func() {
            return callback_func;
        }
     
        public void setCallback_func(String callback_func) {
            this.callback_func = callback_func;
        }
    }



    단일사진 첨부 컨트롤러


    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
    //단일파일업로드
        @RequestMapping("/common/photoUpload.do")
        public String photoUpload(HttpServletRequest request, PhotoVo vo){
            String callback = vo.getCallback();
            String callback_func = vo.getCallback_func();
            String file_result = "";
            try {
                if(vo.getFiledata() != null && vo.getFiledata().getOriginalFilename() != null && !vo.getFiledata().getOriginalFilename().equals("")){
                    //파일이 존재하면
                    String original_name = vo.getFiledata().getOriginalFilename();
                    String ext = original_name.substring(original_name.lastIndexOf(".")+1);
                    //파일 기본경로
                    String defaultPath = request.getSession().getServletContext().getRealPath("/");
                    //파일 기본경로 _ 상세경로
                    String path = defaultPath + "resource" + File.separator + "photo_upload" + File.separator;              
                    File file = new File(path);
                    System.out.println("path:"+path);
                    //디렉토리 존재하지 않을경우 디렉토리 생성
                    if(!file.exists()) {
                        file.mkdirs();
                    }
                    //서버에 업로드 할 파일명(한글문제로 인해 원본파일은 올리지 않는것이 좋음)
                    String realname = UUID.randomUUID().toString() + "." + ext;
                ///////////////// 서버에 파일쓰기 ///////////////// 
                    vo.getFiledata().transferTo(new File(path+realname));
                    file_result += "&bNewLine=true&sFileName="+original_name+"&sFileURL=/resource/photo_upload/"+realname;
                } else {
                    file_result += "&errstr=error";
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            return "redirect:" + callback + "?callback_func="+callback_func+file_result;
        }



    만약 IE 10이상이며 다중파일 업로드 화면이 출력된다 하시면

    attach_photo.js 파일의 41번째 줄을 보시면 checkDragAndDropAPI() 함수내에 존재하는



    1
    bSupportDragAndDropAPI = true;



    1
    bSupportDragAndDropAPI = false;



    다중사진 첨부 컨트롤러

    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
    45
    46
    47
    48
    49
    50
    51
    52
    //다중파일업로드
        @RequestMapping("/common/multiplePhotoUpload.do")
        public void multiplePhotoUpload(HttpServletRequest request, HttpServletResponse response){
            try {
                 //파일정보
                 String sFileInfo = "";
                 //파일명을 받는다 - 일반 원본파일명
                 String filename = request.getHeader("file-name");
                 //파일 확장자
                 String filename_ext = filename.substring(filename.lastIndexOf(".")+1);
                 //확장자를소문자로 변경
                 filename_ext = filename_ext.toLowerCase();
                 //파일 기본경로
                 String dftFilePath = request.getSession().getServletContext().getRealPath("/");
                 //파일 기본경로 _ 상세경로
                 String filePath = dftFilePath + "resource" + File.separator + "photo_upload" + File.separator;
                 File file = new File(filePath);
                 if(!file.exists()) {
                    file.mkdirs();
                 }
                 String realFileNm = "";
                 SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMddHHmmss");
                 String today= formatter.format(new java.util.Date());
                 realFileNm = today+UUID.randomUUID().toString() + filename.substring(filename.lastIndexOf("."));
                 String rlFileNm = filePath + realFileNm;
                 ///////////////// 서버에 파일쓰기 ///////////////// 
                 InputStream is = request.getInputStream();
                 OutputStream os=new FileOutputStream(rlFileNm);
                 int numRead;
                 byte b[] = new byte[Integer.parseInt(request.getHeader("file-size"))];
                 while((numRead = is.read(b,0,b.length)) != -1){
                    os.write(b,0,numRead);
                 }
                 if(is != null) {
                    is.close();
                 }
                 os.flush();
                 os.close();
                 ///////////////// 서버에 파일쓰기 /////////////////
                 // 정보 출력
                 sFileInfo += "&bNewLine=true";
                 // img 태그의 title 속성을 원본파일명으로 적용시켜주기 위함
                 sFileInfo += "&sFileName="+ filename;;
                 sFileInfo += "&sFileURL="+"/resource/photo_upload/"+realFileNm;
                 PrintWriter print = response.getWriter();
                 print.print(sFileInfo);
                 print.flush();
                 print.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    cs


    Result



    참조블로그: http://hellogk.tistory.com/62 

Designed by Tistory.