CKEditor를 이용한 이미지 업로드

먼저 톰캣의 server.xml에 경로를 추가해주어야 한다

docBase에는 외부폴더 설정경로

path의 주소는 localhost:9090/이부분/이미지파일이름 형식으로 입력

path의 주소는 이미지 주소를 뜻함

      <!-- 외부 폴더에 저장하도록 서버에 요청 -->
      <Context docBase="C:\\Dev\\upload\\ckeditor" path="/upload/" reloadable="true"/>
<script type="text/javascript" src="/resources/bower_components/ckeditor/ckeditor.js"></script>
<script>

	$(document).ready(function(){

		// ckeditor 환경설정
		var ckeditor_config = {
			resize_enabled : false,
			enterMode : CKEDITOR.ENTER_BR,
			shiftEnterMode : CKEDITOR.ENTER_P,
			toolbarCanCollapse : true,
			removePlugins : "elementspath",
			filebrowserUploadUrl: '/admin/product/imageUpload' //업로드 탭기능추가 속성. post 주소로 사용됨
		}

		CKEDITOR.replace("pdt_detail", ckeditor_config);
    });
    
</script>

위의 filebrowserUploadUrl에 나오는 주소로 PostMapping로 연결 시켜준다

그리고 컨트롤러에 생성

아래의 경우 프로젝트 외부에 저장하도록 설계

내부버전의 변수로 변경하면 프로젝트 내부에 저장 가능

//CKEditor 웹 에디터를 통한 이미지 업로드 작업(상세설명에서 사용하는 설명이미지 파일)
// 이미지 파일 선택하는 창에서 <input name="upload">로 확인됨.
@PostMapping("/imageUpload")
public void imageUpload(HttpServletRequest req, HttpServletResponse res, MultipartFile upload) {

    // 입출력스트림방식으로 파일 업로드 구현
    // request : 
    // response : 

    OutputStream out = null;
    PrintWriter printWriter = null;

    // 클라이언트의 브라우저에게 보내는 정보
    res.setCharacterEncoding("utf-8");
    res.setContentType("text/html; charset=utf-8");

    try {
        String fileName = upload.getOriginalFilename(); // 클라이언트에서 업로드한 원본파일명
        byte[] bytes = upload.getBytes(); // 업로드 파일

        // 서버측의 업로드 폴더 경로 설정작업. 프로젝트 내부 or 외부
        // 내부 : 톰캣이 war 파일로 리눅스서버에 배포를 할 경우, 톰캣이 재시작하면 기존 upload폴더를 삭제할 수 있다

        // 내부버전
        String uploadTomcatTempPath = req.getSession().getServletContext().getRealPath("/") + "resources\\upload\\";
        log.info("톰캣 물리적 경로 : " + uploadTomcatTempPath);

        // 외부버전
        String uploadPath = "C:\\Dev\\upload\\ckeditor\\"; // 톰캣의 server.xml에 설정정보 참고

        log.info("톰캣 물리적 경로 : " + uploadPath);

        uploadPath = uploadPath + fileName;

        out = new FileOutputStream(new File(uploadPath)); // 파일입출력스트림 객체생성(실제폴더에 파일생성됨)
        out.write(bytes); // 출력스트림에 업로드된 파일을 가르키는 바이트배열을 쓴다. 업로드된 파일크기

        // CKEditor에게 보낼 파일정보작업

        printWriter = res.getWriter();

        // 클라이언트에서 요청할 이미지 주소정보
        String fileUrl = "/upload/" + fileName; // 톰캣의 server.xml에 설정정보 참고

        // {"filename":"abc.gif", "uploaded":1, "url":"/upload/abc.gif"} json포맷
        printWriter.println("{\"filename\":\"" + fileName + "\", \"uploaded\":1,\"url\":\"" + fileUrl + "\"}");
        printWriter.flush(); // 전송 (return과 같은 역할: 클라이언트로 보냄)


    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } finally {
        if(out != null) {
            try {
                out.close();
            } catch(IOException e) {
                e.printStackTrace();
            }
        }
        if(printWriter != null) {
            printWriter.close();
        }
    }

}

댓글남기기