프로젝트/G.O.A.T(여행 스케줄러)

여행 게시판 해결! ckEditor4

찌서니 2022. 1. 16. 14:53
🔔 22월 01월 13일
✔ 사람들이 많이 사용한 에디터 검색
✔ 에디터 뭐로 사용할지 결정
✔ 썸네일 사진으로 할지, 리스트로 할지(팀원이랑 상의)
✔ 여행게시판 조회
✔ 여행게시판 수정
✔ 여행게시판 삭제

 

인터넷 쳐봤더니 사람들이 많이 사용했던게 ck에디터여서

원래는 5버전으로 최신꺼를 쓸까하다가 4버전이 데이터가

더 많을거 같아서 우선 있는거 없는거 다 인터넷창 띄워놓고,

에디터 홈페이지 들어가보면 full 버전도 있고, basic에다 내가 하고싶은거

추가해도 된다고했는데 다운로드받아서 넣어서도 해봤는데

그거보다는 full 버전 스크립트 한줄로 사용하는게 낫겠다고 생각해서

 

<script src="//cdn.ckeditor.com/4.17.1/full/ckeditor.js"></script>

이거 한줄 쓰구, textarea 부분은

<textarea class="form-control" name="t_content" id="t_content"></textarea>
	<script type="text/javascript">
 		CKEDITOR.replace('t_content'
 			, {filebrowserUploadUrl:'imageUpload.do'
            , height: 500, width: 1000
         });
</script>

이렇게 쓰면

그리고 filebrowserUploadUrl를 써줘야 사진 올릴수 있는 부분이 생긴다.

처음에 스크립트만 쓰면 업로드가 없음!

ckEditor의 방법은 업로드로 파일을 선택한후 서버로 전송을 해서

거기서 url 받아서 뿌려준다.

이러한 틀이 생성됨!!!

그리고 컨트롤러 부분이 진짜 제일 문제였는데....

구글링을 너무 잘했고, 어떤분이 티스토리에 좋은 코드를 올려주셔서

다행히 해결이 쉽게 됐다ㅜㅜ 진짜 감격!!!!

 

 

@RequestMapping(value="trip/imageUpload.do", method = RequestMethod.POST) 
	public void imageUpload(HttpServletRequest request, HttpSession session,
			HttpServletResponse response, MultipartHttpServletRequest multiFile , 
			@RequestParam MultipartFile upload) throws Exception{ 
		// 랜덤 문자 생성 
		UUID uid = UUID.randomUUID();
		
		OutputStream out = null; 
		PrintWriter printWriter = null; 
		
		//인코딩 
		response.setCharacterEncoding("utf-8");
		response.setContentType("text/html;charset=utf-8");
		
		try{ 
			//파일 이름 가져오기 
			String fileName = upload.getOriginalFilename();
			byte[] bytes = upload.getBytes(); 
			
			//이미지 경로 생성 
			String real = session.getServletContext().getRealPath("/resources/tripPhoto");
			String ckUploadPath = real + "/" + uid + "_" + fileName; 
			File folder = new File(real);
			
			//해당 디렉토리 확인 
			if(!folder.exists()){ 
				try{ folder.mkdirs(); // 폴더 생성 
				}catch(Exception e){ 
					e.getStackTrace(); 
					} 
				}
			
			out = new FileOutputStream(new File(ckUploadPath)); 
			out.write(bytes); 
			out.flush(); // outputStram에 저장된 데이터를 전송하고 초기화 
			
			String callback = request.getParameter("CKEditorFuncNum"); 
			printWriter = response.getWriter(); 
			String fileUrl = "ckImgSubmit.do?uid=" + uid + "&fileName=" + fileName; // 작성화면 
			
			// 업로드시 메시지 출력
			printWriter.println("{\"filename\" : \""+fileName+"\", \"uploaded\" : 1, \"url\":\""+fileUrl+"\"}"); 
			printWriter.flush(); 
			
		}catch(IOException e){ 
			e.printStackTrace(); 
			} finally { 
				try { if(out != null) { out.close(); } 
				if(printWriter != null) { printWriter.close(); } 
				} catch(IOException e) { e.printStackTrace(); } 
			} 
		return; 
	}
	
	@RequestMapping(value="trip/ckImgSubmit.do") 
	public void ckSubmit(@RequestParam(value="uid") String uid 
			, @RequestParam(value="fileName") String fileName
			, HttpSession session, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{ 
		
		//서버에 저장된 이미지 경로 
		String real = session.getServletContext().getRealPath("/resources/tripPhoto");
		String sDirPath = real+ "/" + uid + "_" + fileName; 
		File imgFile = new File(sDirPath); 
		
		//사진 이미지 찾지 못하는 경우 예외처리로 빈 이미지 파일을 설정한다. 
		if(imgFile.isFile()){ byte[] buf = new byte[1024]; 
		int readByte = 0; 
		int length = 0; 
		byte[] imgBuf = null; 
		
		FileInputStream fileInputStream = null; 
		ByteArrayOutputStream outputStream = null; 
		ServletOutputStream out = null; 
		
		try{ 
			fileInputStream = new FileInputStream(imgFile); 
			outputStream = new ByteArrayOutputStream(); 
			out = response.getOutputStream(); 
			
			while((readByte = fileInputStream.read(buf)) != -1){ 
				outputStream.write(buf, 0, readByte); 
				} 
			
			imgBuf = outputStream.toByteArray(); 
			length = imgBuf.length; 
			out.write(imgBuf, 0, length); 
			out.flush(); 
			
		}catch(IOException e){ 
			e.getMessage();
		}finally { 
			outputStream.close();
			fileInputStream.close();
			out.close();
			} 
		} 
	}

이렇게해서 올리면 DB에는

이런식으로 아예 태그로 올라가게 돼서 불러올때도

태그로 불러와져서 글씨크기, 색 이런거를 설정해서 올려도

그대로 불러와짐!!!!

 

 

이번에는 내가 고객문의, 공지사항 게시판을 만들었기 때문에

로직이 비슷해서 입력이 된 후에 수정/삭제/조회는 소스를 붙여서

sql만 조금 손보고 했기 때문에 쉽게 했다.

이제 해야될거는 대댓글을 여행게시판에도 추가하는건데,

이거도 로직도를 다 이해했고 짜여져 있기 때문에 얼마 안 걸릴거 같고,

좋아요!(추천수)는 내가 해본게 아니여서 조금 시간이 걸릴거 같고,,,

조회수나 추천수가 높은거 3개를 미리 보여주기로 했는데 썸네일을 따로 띄울것인지

아니면 게시판에 들어있는 사진을 띄울지는 팀원이랑 상의를 해봐야된다.