가자공부하러!

CKEditor5 - 클립보드 이미지 복붙 관련 코드 본문

공부/웹

CKEditor5 - 클립보드 이미지 복붙 관련 코드

오피스엑소더스 2019. 11. 11. 14:46

1. 요약

  > CKEditor에 클립보드 이미지를 붙여넣거나, 이미지 업로드 버튼을 통해 textarea에 이미지를 올리면 Ajax 통신을 통해 해당 이미지 파일을 즉시 저장

 

2. 코드

  > JSP

   - 파일 업로드 URL : /ck/fileupload

   - ctx는 ContextPath

<script src="https://cdn.ckeditor.com/ckeditor5/12.4.0/classic/ckeditor.js"></script>
<script src="<%=ctx%>/vendor/ckeditor/ckfinder/ckfinder.js"></script>

<div class="editor_wrap">
	<textarea name="content" id="review_editor" placeholder="후기 내용을 입력해 주세요."></textarea>
</div>

<!-- CKEditor -->
<script type="text/javascript">
var myEditor;
ClassicEditor
	.create( document.querySelector( '#review_editor' ), {
		ckfinder: {
	        uploadUrl: '/ck/fileupload' // 내가 지정한 업로드 url (post로 요청감)
		},
		alignment: {
            options: [ 'left', 'center', 'right' ]
        }
	} )
	.then( editor => {
        console.log( 'Editor was initialized', editor );
        myEditor = editor;
    } )
	.catch( error => {
	    console.error( error );
	} );
</script>

  > Controller

   - 수행 결과로 json형태의 문자열을 리턴

package com.rhymes.app.common.controller;

import java.io.File;
import java.io.IOException;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.io.FileUtils;
import org.json.JSONObject;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.rhymes.app.common.util.FUpUtil;

@Controller
public class FileManageController {
	
	/**ck에디터 파일업로드 이벤트 발생 시 처리
	 * @param model
	 * @param fileload
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/ck/fileupload", method = {RequestMethod.POST, RequestMethod.GET})
	public String fileUpload(Model model,  
	        @RequestParam(value="upload", required = false) MultipartFile fileload,
	        HttpServletRequest req) {
		
		//서버에 파일을 저장할 때에는 파일명을 시간값으로 변경
	    //DB에 저장할 때에는 원본 파일명과 시간값을 모두 저장
	    //filename 취득
	    String filename = fileload.getOriginalFilename();
	    
	    //upload 경로 설정(tomcat realpath)
	    String fuploadPath = req.getServletContext().getRealPath("/upload/editor");
	 
	    //폴더 경로 설정
	    String newfilename = FUpUtil.name(filename);
	    
	    //업로드 수행	    
	    File file = new File(fuploadPath + "/" + newfilename);
	    
	    try {
	        //실제 파일이 업로드 되는 부분
	        FileUtils.writeByteArrayToFile(file, fileload.getBytes() );	        
	        return "{ \"uploaded\" : true, \"url\" : \"http://112.169.197.59:18080/upload/editor/" + newfilename + "\" }";
	    } catch (IOException e) {
	        // TODO Auto-generated catch block
	    	return "{ \"uploaded\" : false, \"error\": { \"message\": \"업로드 중 에러가 발생했습니다. 다시 시도해 주세요.\" } }";
	    }
	}
}

Comments