반응형

진짜 한 3일 삽질 했엇던 

CK에디터 이미지 업로드 방금 성공해서 

 

드디어 포스팅을한다. 

방법은 스프링레거시 프로젝트 내에서 폴더를 생성하여 그것을 저장하여 url화 하여 json으로 ck에디터로 뿌려주면 된다. 

 

그럼 이제 방법을 살펴보자 .

 

https://ckeditor.com/ckeditor-4/?ppc_keyword=ckeditor4&gclid=CjwKCAjw6dmSBhBkEiwA_W-EoEfmmdMseX5ETbtapK8JIJnxKQiqjfQKMXiY_8d_9S3464Sc5qG_mhoCQ1oQAvD_BwE 

 

CKEditor 4 | Visual Text Editor for HTML

Fully Customizable WYSIWYG HTML Editor with the biggest number of Rich Text features. Enterprise-grade with 70 languages and the approval of millions.

ckeditor.com

 

우선 위에 보이는 곳으로 가서 ck에디터를 다운받자 

다운 받은 후에 프로젝트 webapp > resources폴더에다 붙혀 넣기 해주자 

 

대략 이런 형태가 될 것이다. 

 

그 후에 view로 가서 적용시킬 jsp페이지로 가준다. 

 

<resources mapping="/ckeditor/**" location="/resources/ckeditor/" />

그전에 servlet-context에서 경로좀 매핑해주자 그래야 편하다. 

 

 

그다음 

 

<script type="text/javascript" src="../resources/ckeditor/ckeditor.js"></script>


          <div class="mb-3" style="width: 50%; margin: 0 auto;">
            <label for="exampleFormControlTextarea1" class="form-label">News Content</label>
            <textarea class="form-control " name="freeboard_content" id="ckeditor" rows="6"></textarea>
          </div>

	 CKEDITOR.replace( 'ckeditor', {//해당 이름으로 된 textarea에 에디터를 적용
         width:'100%',
         height:'400px',
         filebrowserUploadUrl:  "fileupload.do"
     });

위처럼 헤드사이에 스크립트 코드를 넣어주고 

 

텍스트에어리어에 id값을 ckeditor로 해준다. (아이디 값은 딱히 상관 없다.)

그 다음 하단 부분 스크립트 태그 사이에 

 

ckeditor로 넣어준다. 

 

그리고 filebrowserUploadUrl:  "fileupload.do" 

요 코드는 컨트롤러랑 연결해 줄 코드 이다. 

 

 

<c:url/> 을 쓰던 컨트롤러랑 연결만 되면 된다. 

 

 

 

그러면 위와 같이 ckeditor가 연결 되었을 것이다.

 

그럼 이제 ck에디터 사용은 끝이고 

컨트롤러를 보자 !

 

그전에 추가해주어야할 api가 있다. 

 

		    <dependency>
		        <groupId>org.apache.commons</groupId>
		        <artifactId>commons-lang3</artifactId>
		        <version>3.4</version>
		    </dependency>
            
        <dependency>
		    <groupId>commons-fileupload</groupId>
		    <artifactId>commons-fileupload</artifactId>
		    <version>1.3.3</version>
		</dependency>
        
        		<dependency>
		    <groupId>com.google.code.gson</groupId>
		    <artifactId>gson</artifactId>
		    <version>2.8.5</version>
		</dependency>

이 세가지 정도면 될거같다. 

 

gson은 말 그대로 구글에서 만든 json을 쉽게 쓸수 있도록 만든 api이다. 

commons-fileupload 파일 업로드 api

commons-lang3 아파치에서 만든 스트링 비교를 쉽게 해줄수 있는 api 이다. 

 

그다음 파일 빈등록을 해주자.

 

파일업로드만 해주면 될거같다. 

	<beans:bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
		
		<!-- 최대 업로드 가능한 바이트 크기(바이트 단위), -1은 제한이 없음을 의미 -->
		<beans:property name="maxUploadSize" value="10485760" />
		
		<!-- 업로드 요청을 변환할 때 사용할 문자 인코딩 방식 -->
		<beans:property name="defaultEncoding" value="utf-8" />
	
	</beans:bean>

servlet-context에 위와 같이 붙혀 넣어주자 빈등록을 하였으면 

이제 컨트롤러로 가보자 

 

컨트롤러를 따로 분리해도 되지만 나는 그냥 기존 컨트롤러에 이어서 작성하였다. 

 

CK에디터 4.8.0부터 파일 전달 방식이 json으로 바뀌었다. 

그래서 바뀐 최신 버전으로 사용했다. 

 

	@ResponseBody
	@RequestMapping(value = "fileupload.do")
    public void communityImageUpload(HttpServletRequest req, HttpServletResponse resp, MultipartHttpServletRequest multiFile) throws Exception{
		JsonObject jsonObject = new JsonObject();
		PrintWriter printWriter = null;
		OutputStream out = null;
		MultipartFile file = multiFile.getFile("upload");
		
		if(file != null) {
			if(file.getSize() >0 && StringUtils.isNotBlank(file.getName())) {
				if(file.getContentType().toLowerCase().startsWith("image/")) {
				    try{
				    	 
			            String fileName = file.getOriginalFilename();
			            byte[] bytes = file.getBytes();
			           
			            String uploadPath = req.getSession().getServletContext().getRealPath("/resources/images/noticeimg"); //저장경로
			            System.out.println("uploadPath:"+uploadPath);

			            File uploadFile = new File(uploadPath);
			            if(!uploadFile.exists()) {
			            	uploadFile.mkdir();
			            }
			            String fileName2 = UUID.randomUUID().toString();
			            uploadPath = uploadPath + "/" + fileName2 +fileName;
			            
			            out = new FileOutputStream(new File(uploadPath));
			            out.write(bytes);
			            
			            printWriter = resp.getWriter();
			            String fileUrl = req.getContextPath() + "/resources/images/noticeimg/" +fileName2 +fileName; //url경로
			            System.out.println("fileUrl :" + fileUrl);
			            JsonObject json = new JsonObject();
			            json.addProperty("uploaded", 1);
			            json.addProperty("fileName", fileName);
			            json.addProperty("url", fileUrl);
			            printWriter.print(json);
			            System.out.println(json);
			 
			        }catch(IOException e){
			            e.printStackTrace();
			        } finally {
			            if (out != null) {
		                    out.close();
		                }
		                if (printWriter != null) {
		                    printWriter.close();
		                }
			        }
				}

			
		}
		
	}
	}

우선 json을 사용하기 위해 생성자를 이용해 성성해준다. 

 

그 후 파일사이즈가 0일 떄 비교 식을 작성해주고 

그안에 또 if문으로 startsWith가 image인 것만 등록 되게 해주었다. 

 

fileName으로 파일명을 넣어주고 

byte[] bytes = file.getBytes(); 로 파일 크기 도 가져온다. 

 

String uploadPath = req.getSession().getServletContext().getRealPath("/resources/images/noticeimg");

 

저장 경로는 서버내 resoureces 내에 images / noticeing로 생성해 주었다. 

 

이제 파일 전송을 클릭하면 여기에 저장될 것이다. 

 

그리고 

 

 File uploadFile = new File(uploadPath);
            if(!uploadFile.exists()) {
             uploadFile.mkdir();
            }

파일 객체를 생성해주고 

폴더가 없다면 생성해준다. 

나중에 심플데이트포멧으로 파일명을 변경 해주어도 될거같다. 

 

    String fileName2 = UUID.randomUUID().toString();
            uploadPath = uploadPath + "/" + fileName2 +fileName;

 

그리고 filename2를 생성하여 uuid로 랜덤값을 생성해준다. 

 

그 후 uploadPath에 붙혀넣어 준다. 

 

그럼 resources/images/noticeimg/uuid랜덤값+파일명

으로 저장될 것이다. 

 

 printWriter = resp.getWriter();

request 객체를 보낸 곳으로 데이터를 전달.

오류 없이 실핼될 경우 success : function()의 매개변수로 들어간다.

 

이제 fileUrl을 만들어보자.

 

String fileUrl = req.getContextPath() + "/resources/images/noticeimg/" +fileName2 +fileName;

 

상대경로로 만들어 준다. 

 

/서버명 혹은 localhost//resources/images/noticeimg/" +fileName2 +fileName;

 

이런식으로 만들어 질 것이다. 

 

그리고 이제 json으로 뿌려주자.

 

 

         System.out.println("fileUrl :" + fileUrl);
            JsonObject json = new JsonObject();
            json.addProperty("uploaded", 1);
            json.addProperty("fileName", fileName);
            json.addProperty("url", fileUrl);
            printWriter.print(json);

 

그리고 메모리 자원관리를 위해

다쓴 메소드는 close로 닫아준다.

 

그럼 정말 끝!

 

정말 애먹었던 부분이 위 경로 때문에 

자꾸 엑박이 뜬다면 경로를 점검 해보자 :) 

 

작동 과정 

 

파일 선택 을 클릭하여 파일을 선택해준다. 

 

 

선택 후 서버로 전송을 눌러주면

 

 

 

이렇게 성공한다. 

 

 

이렇게 에디터에 잘 들어간다.

 

그리고 이거 그대로 파라미터로 태워서 인서트를 시켜주면 된다. 

 

 

이렇게 아주 잘 뜨는게 볼 수 있을 거다.

 

이거 한다고 거의 2틀을 고생했던거 같다. 

 

페이징부터 참 해보고싶은건 많이만 

자바 기초를 정말 틈틈히 다시 공부해야겠다. 

 

정말 너무 해깔린다. 

 

파이팅 하자 ! 

https://github.com/MoonSeokHyun

반응형

+ Recent posts