-
네이버 스마트 에디터 연동 + SPRING MVCWeb (Spring ) 2016. 8. 18. 23:56
네이버 스마트 에디터 다운로드
http://dev.naver.com/projects/smarteditor/download
1<mvc:resources mapping="/**" location="/webapp/" />위의 코드를 자신의 servelet에 넣어준다.
다운로드가 완료되었다면 압축해제한 파일을 자신의 webapp root에 놓는다.
모든 리소스(자원들은) webapp에서 끌어온다는 것.
위와 같은 구조이다. 이어서 계속
12<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단에 다음과 같이 스크립트 선언1234567891011121314151617181920212223242526272829$(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() 함수를 보게 되면
123sUrl : location.href.replace(/\/[^\/]*$/, '') + '/file_uploader.php', //샘플 URL입니다.sCallback : location.href.replace(/\/[^\/]*$/, '') + '/callback.html', //업로드 이후에 iframe이 redirect될 콜백페이지의 주소1번라인 본인 파일업로드 컨트롤러
2번라인은 콜백 Url
수정
12sUrl : '/common/photoUpload.do', //변경 URL입니다.sCallback : '/naver_editor/sample/photo_uploader/callback.html', //업로드 이후에 iframe이 redirect될 콜백페이지의 주소이어서 336번 라인 html5Upload() 함수를 보게되면
마찬가지로 자신의 다중파일업로드 경로로 수정
1sUploadURL= 'html5upload.php'; //다중파일업로드 URL1sUploadURL= '/common/multiplePhotoUpload.do'; //다중파일업로드 URL위에서 수정한 서버단을 이제 만들어보자
PhotoVo.java
123456789101112131415161718192021222324252627282930313233343536373839404142434445package 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 URLprivate 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;}}단일사진 첨부 컨트롤러
12345678910111213141516171819202122232425262728293031323334//단일파일업로드@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() 함수내에 존재하는
1bSupportDragAndDropAPI = true;1bSupportDragAndDropAPI = false;다중사진 첨부 컨트롤러
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152//다중파일업로드@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
'Web (Spring )' 카테고리의 다른 글
[MVC게시판] 게시판 글 수정&삭제 (0) 2016.08.19 [MSSQL] SPRING + MAVEN + MSSQL 연동방법 (0) 2016.08.19 팝업창에서 POST방식 (0) 2016.08.18 [MVC게시판] 게시판 글보기 (0) 2016.08.18 [MVC게시판] 게시판 글쓰기 (0) 2016.08.09