728x90
반응형

네이버에서 제공하는 무료 웹 에디터인 스마트 에디터를 게시판에 적용해 봅니다.

http://dev.naver.com/projects/smarteditor/download 사이트에 접속하여 스스를 다운로드 받는다.

나는 SmartEditor2.0 Basic (2.3.10.11329 - 보안패치...)를 다운로드 하였다. (SE2.3.10.O11329.zip)


1. 작업을 하고자하는 프로젝트의 WebContent 디렉토리 밑에 smarteditor라는 폴더를 만든 후, 압축을 푼 파일들을 갖다 놓는다.


2. 나는 스마트 에디터를 사용하여 글을 작성하는 파일을 WebContent/s/1/1-1.jsp로 하였다. 주의할 점은 경로를 잘 맞추어야 한다는 것이다.


2.1 Include 파일의 내용은 아래와 같다.

<script type="text/javascript" src="../../js/jquery/jquery-1.11.3.min.js"></script>

<script type="text/javascript" src="../../smarteditor/js/HuskyEZCreator.js" charset="utf-8"></script>

<script type="text/javascript" charset="utf-8" src="../../js/s/1/1-1.js"></script>

경로는 상대경로를 사용하였다.


2.2 에디터 샘플 html 파일

<form action="send.jsp" method="post" id="frm">

    <textarea name="smarteditor" id="smarteditor" rows="10" cols="100" style="width:756px; height:412px;">

    </textarea>

    <input type="button" id="savebutton" value="서버전송" />

</form>


  width와 height는 자신의 공간의 크기에 맞추어 변경한다.


3. 에디터 관련 스크립트 코드 (1-1.js)

  

function subInit() {

//전역변수선언

    var editor_object = [];

    var ctx = getContextPath();

     

    nhn.husky.EZCreator.createInIFrame({

        oAppRef: editor_object,

        elPlaceHolder: "smarteditor",

        sSkinURI: ctx + "/smarteditor/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();

    })


    function getContextPath() {

    return window.location.pathname.substring(0, window.location.pathname.indexOf("/",2));

    }

}


4. send.jsp 코드는 아래와 같다.

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>

<%

//한글 인코딩을 위한 UTF-8 설정

request.setCharacterEncoding("utf-8");

out.println("에디터 결과");  

out.println(request.getParameter("smarteditor"));

%>


5. 사진으로 이미지 파일을 업로드하는 것을 추가해 보면 다음과 같다. 본문에 이미지를 추가할 수 있다.

5.1 필요한 라이브러리를 WebContent/WEB-INF/lib에 추가

  - Apache Commons FileUpload : commons-fileupload-1.3.1.jar

  - Apache Commons IO : commons-io-2.4.jar


5.2 Single file upload와 Multiple file upload : 나는 chrome 브라우저로 해 보았다.

  - smarteditor/photo_uploader/popup/attach_photo.js checkDragAndDropAPI 수정

    if(!!oNavigator.safari && oNavigator.version <= 5){

bSupportDragAndDropAPI = false;

    }else{

bSupportDragAndDropAPI = true; // multiple 파일 업로드

// bSupportDragAndDropAPI = false; // single 파일 업로드

    }


5.3 Single file upload

5.3.1 attach_photo.js callFileUploader() 함수 수정

  - 첨부 사진을 서버의 WebContent/upload 디렉토리에 저장하고, 본문에 사진을 배치한다.

  - file_uploader.jsp 파일을 WebContext/smarteditor/photo_uploader/popup 디렉토리에 둔다.

  sUrl  : location.href.replace(/\/[^\/]*$/, '') + '/file_uploader.jsp', //샘플 URL입니다.

  sCallback : location.href.replace(/\/[^\/]*$/, '') + '/callback.html', //업로드 이후에 iframe이 redirect될 콜백페이지의 주소


5.3.2 file_uploader.jsp

  사진 파일이 한글을 포함할 경우, 추가로 고려하여야 한다.(추후)

<%@page import="java.io.FileOutputStream"%>

<%@page import="java.util.UUID"%>

<%@page import="java.io.OutputStream"%>

<%@page import="java.io.InputStream"%>

<%@page import="java.io.File"%>

<%@page import="org.apache.commons.fileupload.FileItem"%>

<%@page import="java.util.List"%>

<%@page import="org.apache.commons.fileupload.disk.DiskFileItemFactory"%>

<%@page import="org.apache.commons.fileupload.servlet.ServletFileUpload"%>

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>

<%

  request.setCharacterEncoding("utf-8");

  String return1="";

  String return2="";

  String return3="";

  String name = "";

  if (ServletFileUpload.isMultipartContent(request)){

    ServletFileUpload uploadHandler = new ServletFileUpload(new DiskFileItemFactory());

    //UTF-8 인코딩 설정

    uploadHandler.setHeaderEncoding("UTF-8");

    List<FileItem> items = uploadHandler.parseRequest(request);

    //각 필드태그들을 FOR문을 이용하여 비교를 합니다.

    for (FileItem item : items) {

      if(item.getFieldName().equals("callback")) {

        return1 = item.getString("UTF-8");

      } else if(item.getFieldName().equals("callback_func")) {

        return2 = "?callback_func="+item.getString("UTF-8");

      } else if(item.getFieldName().equals("Filedata")) {

        //FILE 태그가 1개이상일 경우

        if(item.getSize() > 0) {

          name = item.getName();

          String ext = item.getName().substring(item.getName().lastIndexOf(".")+1);

          //파일 기본경로

          String defaultPath = request.getServletContext().getRealPath("/");

          //파일 기본경로 _ 상세경로

          String path = defaultPath + "upload" + File.separator;

                 

          File file = new File(path);

                 

          //디렉토리 존재하지 않을경우 디렉토리 생성

          if(!file.exists()) {

            file.mkdirs();

          }

          //서버에 업로드 할 파일명(한글문제로 인해 원본파일은 올리지 않는것이 좋음)

          String realname = UUID.randomUUID().toString() + "." + ext;

          ///////////////// 서버에 파일쓰기 ///////////////// 

          InputStream is = item.getInputStream();

          OutputStream os=new FileOutputStream(path + realname);

          int numRead;

          byte b[] = new byte[(int)item.getSize()];

          while((numRead = is.read(b,0,b.length)) != -1){

            os.write(b,0,numRead);

          }

          if(is != null)  is.close();

          os.flush();

          os.close();

          ///////////////// 서버에 파일쓰기 /////////////////

          String root = request.getContextPath();


          return3 += "&bNewLine=true&sFileName="+name+"&sFileURL=" + root + "/upload/"+realname;

        }else {

          return3 += "&errstr=error";

        }

      }

    }

  }

  response.sendRedirect(return1+return2+return3);

%>


5.4 Multiple file upload

  - HTML5를 이용한 다중 파일 업로드를 구현 : 다중 파일을 본문에 추가


5.4.1 attach_photo.js html5Upload() 함수 수정

sUploadURL= 'file_uploader_html5.jsp'; //upload URL


5.4.2 file_uploader_html5.jsp 작성

  파일을 upload 디렉토리에 저장하고, 본문에 배치


<%@page import="java.util.ArrayList"%>

<%@page import="java.util.List"%>

<%@page import="com.talanton.homepage.common.utilities.SmartEditorImageManager"%>

<%@page import="com.talanton.homepage.pds.model.AddRequest"%>

<%@page import="java.io.FileOutputStream"%>

<%@page import="java.util.UUID"%>

<%@page import="java.io.OutputStream"%>

<%@page import="java.io.InputStream"%>

<%@page import="java.io.File"%>

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>

<%

String sFileInfo = "";

//파일명 - 싱글파일업로드와 다르게 멀티파일업로드는 HEADER로 넘어옴 

String name = request.getHeader("file-name");

String ext = name.substring(name.lastIndexOf(".")+1);

//파일 기본경로

String defaultPath = request.getServletContext().getRealPath("/");

//파일 기본경로 _ 상세경로

String path = defaultPath + "upload" + File.separator;

File file = new File(path);

if(!file.exists()) {

 file.mkdirs();

}

String realname = UUID.randomUUID().toString() + "." + ext;

InputStream is = request.getInputStream();

String storedFileName = path + realname;

OutputStream os=new FileOutputStream(storedFileName);

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();

String root = request.getContextPath();

sFileInfo += "&bNewLine=true&sFileName="+ name+"&sFileURL=" + root + "/upload/"+realname;

out.println(sFileInfo);

%>


경로를 잘 맞추어 주는 것이 중요하다.


참조 글 : http://hellogk.tistory.com/62http://hellogk.tistory.com/63

728x90
반응형
블로그 이미지

nineDeveloper

안녕하세요 현직 개발자 입니다 ~ 빠르게 변화하는 세상에 뒤쳐지지 않도록 우리모두 열심히 공부합시다 ~! 개발공부는 넘나 재미있는 것~!

,