2010년 11월 15일 월요일

Ckeditor를 ASP에서 사용하기

ckeditor를 asp에 적용하는 작업을 진행 중입니다.
ckfinder를 이용해서 이미지와 플래시를 업로드 하는데
파일은 정상적으로 업로드 되는데 컴포넌트가 없다고 나오는 군요
메시지 : It was not possible to complete the request (Error Unable th find an image manipulation component)
구글과 네이버를 들락 날락 결국은 실패하고 다른 에디터를 사용할까 하다

http://docs.cksource.com/
위의 사이트에 개발 가이드 문서가 있더군요
ckfinder적용하는 것은 포기하고 직접 파일 업로드 페이지를 구현했습니다.

1. 먼저 ckeditor(위지윅 에디터)를 다운 받습니다.
    ckeditor - http://ckeditor.com/download

2. ckeditor 를 사용하는 페이지에 <script type="text/javascript" src="/ckeditor/ckeditor.js"></script>를 추가하고 에디터를 사용할 부분에
<textarea name="editor1"></textarea>
<script type="text/javascript">
    CKEDITOR.replace('editor1',
    {
    toolbar: 'Full',
    uiColor: '#9AB8F3',
    filebrowserUploadUrl: '/upload.asp?type=Files',
    filebrowserImageUploadUrl: '/upload.asp?type=Images',
    filebrowserFlashUploadUrl: '/upload.asp?type=Flash'
    }
);
</script>
위와 같이 넣어주면 ckeditor 를 사용하고자 하는 페이지에 불러올 수 있습니다.
개발문서 참조 하시면 형태는 다양하게 변경할 수 있습니다.

filebrowserUploadUrl / filebrowserImageUploadUrl / filebrowserFlashUploadUrl 에서 설정한 페이지에서 파일 업로드를 구현해 주시면 됩니다.
위의 프로퍼티를 입력하지 않은 경우 업로드 하는 부분이 나타나지 않습니다.
이미지나 플래쉬 서버로 업로드 하기 위해서 반드시 입력하세요
저는 귀찮아서 루트에 업로드 하는 파일을 만들었습니다. ^^

여기 까지 설정하는 부분은 끝입니다.

3. 업로드 파일 구현
기본적으로 업로드 파일로 type 값 넘어오고요
CKEditorFuncNum, CKEditor, langCode, upload .....  필요한 값은 이정도면 됩니다.
ckfinder 의 경우는 타입값에 따라서 Flash / Images / Files 폴더로 나눠서 저장하더군요
하지만 귀찮은 관계로 한 폴더에 모두 저장.. ㅋㅋ
대충 대충하는 만성피로 개발자.. ㅋㅋ

upload.asp 소스입니다.
참고로만 보시면 될것 같습니다.
<%
    Dim funcNum
    Dim CKEditor
    Dim langCode
    Dim fileUrl
    Dim message

    ' 파일 중복을 제거 하기 위해 고정 사이트 만큼 특정 문자를 채워 주는 함수
    Public Function LeftFillString ( strValue, fillChar, makeLength )
        Dim strRet
        Dim strLen, diff, i
       
        strRet  = ""
        strLen  = Len(strValue)
        diff    = CInt(makeLength) - strLen
       
        if diff > 0 then
            for i=1 to diff
                strRet = strRet & CStr(fillChar)
            next
        end if
       
        LeftFillString = strRet & CStr(strValue)
    End Function

 '유니크한 파일명 만들기
 Public Function MakeUniqueFileName( strPrename )
  Dim strFilename
  Dim dtNow
  dtNow = now()
  Randomize()
  strFilename = strPrename
  strFilename = strFilename & Year(dtNow)
  strFilename = strFilename & LeftFillString( Month(dtNow),   "0", 2 )
  strFilename = strFilename & LeftFillString( Day(dtNow),     "0", 2 )
  strFilename = strFilename & "_"
  strFilename = strFilename & LeftFillString( Hour(dtNow),    "0", 2 )
  strFilename = strFilename & LeftFillString( Minute(dtNow),  "0", 2 )
  strFilename = strFilename & LeftFillString( Second(dtNow),  "0", 2 )
  strFilename = strFilename & "_" 
  strFilename = strFilename & LeftFillString ( Int(Rnd * 1000000), "0", 7 )
  MakeUniqueFileName = strFilename
 End Function

 ' 파일 확장자 추출
 Function GetFileExt( strFilename )
  Dim strExt
  Dim nPos
  nPos = InStrRev( strFilename, ".", -1, 1 ) '// Text Compare
  if nPos > 0 then
   strExt = Mid( strFilename, nPos+1 )
  end if
  GetFileExt = strExt
 End Function

    ' 변수들은 위에서 말한 개발자 가이드 문서에서 뽑았습니다.
    ' Required: anonymous function number as explained above.
    funcNum = Request("CKEditorFuncNum")
    'Optional: instance name (might be used to load specific configuration file or anything else)
    CKEditor = Request("CKEditor")
    ' Optional: might be used to provide localized messages
    langCode = Request("langCode")
    ' Check the $_FILES array and save the file. Assign the correct path to some variable ($url).
    'fileUrl = ""
    ' Usually you will assign here something only if file could not be uploaded.
    'message = "성공적으로 파일 업로드"

    ' DEXT Upload를 사용하고 있습니다.
    Set Upload = Server.CreateObject("DEXT.FileUpload")
    Upload.DefaultPath = Server.MapPath ("/data/ckeditor")
    Dim folderPath
    folderPath = Server.MapPath("/data/ckeditor/images/")
    upload_filename = Upload("upload").Filename
    if IsNull(Upload("upload")) or Upload("upload").FileLen <= 0 then
        upload_filename = ""
        img_filesize = 0
        message = "업로드 파일이 존재하지 않습니다."
    else
        upload_filename = MakeUniqueFileName("upload") & "." & GetFileExt(upload_filename)
        img_filesize = Upload("upload").FileLen
        if img_filesize > 0 then
            ' 확장자 체크 해야 하는데 귀찮아서
            ' Request("type") 으로 Images / Flash 구별해서 확장자 추출함수인 GetFileExt(upload_filename) 이걸로 체크하면 되겠죠
            ' 이미지는 jpg, gif, png..   플래쉬는 swf 파일만.. ㅎㅎㅎ
            ' 만성피로와 귀찮음으로 그냥 넘어가기..
            Upload("upload").SaveAs folderPath & "\" & upload_filename
            message = "정상적으로 파일을 업로드했습니다."
        else
            message = "업로드 파일 사이즈가 0입니다."
        end if
    end if
   
    fileUrl = "/data/ckeditor/images/" & upload_filename
%>
<script type="text/javascript">
    // 가장 중요한 부분인것 같군요
    // ckeditor의 순번과 유효한 파일 경로만 넘기면 자동으로 이미지나 플래쉬 속성 변경 탭으로 이동합니다.
    window.parent.CKEDITOR.tools.callFunction(<%=funcNum %>, '<%=fileUrl %>', '<%=message %>');
    history.go(-1);
</script>

저도 여기 저기 찾다 너무 고생을 많이해서
혹시나 저 같은 사람이 있으면 안되니 이렇게 올립니다.

댓글 3개:

  1. 님의 아름다운 배려로 헤메던 숙제를 끝냈습니다. 감사합니다.

    답글삭제
  2. 많은 도움이 됐습니다 감사합니다.

    답글삭제