2017년 5월 31일 수요일

C#, WebForm : 썸머노트(summernote) 에 이미지 업로드 기능 달기


이전에 썸머 노트를 사용해 보았다.

참고 : 위지윅 에디터 (Wysiwyg Editor) 썸머노트(summernote)

문서 작성 까지는 잘 되지만, 이미지를 삽입할때 문제가 된다.


툴 아이콘중 그림 표시를 클릭해보면....


일반적인 이미지 선택창이 나오고 여기서 이미지를 지정하면...


이렇게 이미지가 잘 들어간다.
하지만, 저기 "소스 보기" 아이콘을 클릭하여 html 소스를 보게 되면...


이렇게 일반적인 이미지 링크가 아닌, Base64 로 인코딩된 문자열이 이미지로 삽입되어 있는 것을 볼수 있다.
즉, 문서내에 이미지가 포함되어 있는 것.

이것도 나름 장점이 많은 방식이긴 하지만, 이렇게 하면 전체적으로 데이터가 많이 늘어나는데다, 이미지 관리도 안되고, 특히나 아주 큰 이미지가 첨부되었을 경우 아예 DB 에 넣지도 못하는 경우까지 생길수 있어 좀 골치 아프다.

이걸 일반적인 이미지 업로드해서 이미지 링크가 되게끔 바꿔 보자.
썸머노트에는 이것을 위해 콜백 함수를 지원한다.


현재 이렇게 되어 있을 텐데, 여기에 콜백 함수를 추가한다.


<%@ Page Language="C#" AutoEventWireup="true" CodeFile="BoardEntry.aspx.cs" Inherits="SummerNote_BoardEntry" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
       
    <!-- include libraries(jQuery, bootstrap) -->
    <link href="http://netdna.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.css" rel="stylesheet">
    <script src="http://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.4/jquery.js"></script>
    <script src="http://netdna.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.js"></script>

    <!-- include summernote css/js-->
    <link href="dist/summernote.css" rel="stylesheet" type="text/css" />
    <script src="dist/summernote.min.js" type="text/javascript"></script>

</head>
<body>
    <form id="form1" runat="server">
    <div>
   
        <div id="summernote">Hello Summernote</div>
   
        <script>
            $(document).ready(function() {
                $('#summernote').summernote({
                    height: 300,
                    callbacks: {
                        onImageUpload: function(files) {
                            sendFile(files[0]);
                        }
                    }
                });

                function sendFile(file) {
                    data = new FormData();
                    data.append("file", file);
                    $.ajax({
                        url: 'GetFile.aspx',
                        data: data,
                        cache: false,
                        type: "POST",
                        contentType: false,
                        processData: false,
                        success: function(url) {
                            $('#summernote').summernote('insertImage', url);
                        }
                    });
                }
            });

            function funcMyHtml() {
                document.getElementById("HiddenField").value = $('#summernote').summernote('code');
            }
       
        </script>

        <asp:HiddenField ID="HiddenField" runat="server" />
        <asp:Button ID="Button1" runat="server" Text="Button" OnClientClick="funcMyHtml()" onclick="Button1_Click" />
    </div>
    </form>
</body>
</html>

이렇게...

참고로 여기서는 "callBacks : " 이라는 속성으로 콜백 함수를 지정하였는데, 인터넷을 뒤져 보면 대부분 그냥 "callBacks : " 없이 그냥 "onImageUpload() " 를 쓰라고 되어 있을 것이다. 근데 언제 부터인지 그렇게 안된다.

심지어는 "insertImage" 지정하는 방식도 다르다.
언제 부터 바뀌었는지는 모르겠지만, 하여튼 현재 (2017-05-31) 공식배포처에서 다운 받은 파일로는 안된다.

이렇게 해 놓았으면 파일을 서버로 전송할 준비는 다 되었다.

이제 서버측에서 파일을 수신하는 기능을 만들어 준다.


파일 수신받을 aspx 파일을 하나 추가해 주고...
(원래 웹서비스를 만드는게 정석이겠으나... 귀찮으니 그냥 만들자.)


단순히 파일을 서버에 저장하는 페이지 이므로 아무런 내용이 필요 없으니 html 은 모두 삭제 하자. 헤더만 남겨 두면 된다.



using System;
using System.IO;

public partial class SummerNote_GetFile : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        foreach (string upload in Request.Files)
        {
            string path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory,"upload");
            string filename = Path.GetFileName(Request.Files[upload].FileName);

            if (!Directory.Exists(path)) Directory.CreateDirectory(path);

            Request.Files[upload].SaveAs(Path.Combine(path, filename));

            Response.Write("http://" + Request.Url.Host + ":" + Request.Url.Port + "/web/upload/" + filename);
        }
    }
}

그러고 나서 비하인드 코드에 파일을 저장하는 루틴을 기록.
이렇게 하면 POST 방식으로 전달한 파일을 서버에 저장 할수 있다.


쉽게 말해서 aspx 파일이 아닌 순수 Html 페이지에서 전달한 파일도 받아서 서버에 저장할수 있는 방식이다.
(여기서 FileUpload.htm 파일은 그냥 파일이 잘 업로드 되고 업로드된 경로가 잘 출력되나 테스트해보는 페이지 일 뿐. 즉, 없어도 상관 없는 파일이다.)

이렇게 해 놓고 썸머노트에서 이미지를 다시 삽입해 보면...


이렇게 이미지 태그 방식으로 이미지가 삽입된 것을 볼수 있다.
(참고로 완전한 Url 이 아니면 아예 이미지가 삽입되지 않는다.)