vue.js/vue.js 라이브러리

[vue.js]quill editor file upload base64에서 DB 저장으로 변경 처리

반응형

서론

지난번 프로젝트에서 사용한 quill editor 에서 이미지 업로드시 base64로 들어가는 부분을 이미지 업로드시 DB 저장으로 변경하는 로직으로 변경했던 방법을 정리하고자 한다.

소스

html

<template>
  <div class="example">
    <quill-editor
      class="editor"
      ref="myTextEditor"
      :disabled="false"
      v-model="content"
      :options="editorOption"
      @ready="onEditorReady($event)"
    />
  </div>
</template>

설명

quill editor에 toolbar에 editorOption으로 setting

@ready를 이용하여 이미지 툴바 제어

script

<script>
import { quillEditor } from "vue-quill-editor";

// import theme style
import "quill/dist/quill.core.css";
import "quill/dist/quill.snow.css";

export default {
  components: {
    quillEditor,
  },
  data() {
    return {
      editorOption: {
        modules: {
          toolbar: {
            container: [
              ["image"],
              [{ header: [1, 2, 3, false] }],
              ["bold", "italic", "underline", "strike", "blockquote"],
            ],
          },
        },
      },
      content: "",
    };
  },
  methods: {
    onEditorReady(editor) {
      // 이미지 메소드 추가
      editor.getModule("toolbar").addHandler("image", this.imageHandler);
      console.log("editor ready!", editor);
    },
    imageHandler() {
      console.log("imageHandler start=============");

      // 1. 이미지를 저장할 input type=file DOM을 만든다.
      const input = document.createElement("input");
      // 속성 써주기
      input.setAttribute("type", "file");
      input.setAttribute("accept", "image/*");
      input.click(); // 에디터 이미지버튼을 클릭하면 이 input이 클릭된다.
      // input이 클릭되면 파일 선택창이 나타난다.

      // input에 변화가 생긴다면 = 이미지를 선택
      input.addEventListener("change", async () => {
        const file = input.files[0];
        console.log("file :", file);

        try {
          // 파일 업로드 api 호출

          const imgUrl = "returnData";

          // 현재 에디터 커서 위치 조회
          const range = this.editor.getSelection();

          // 커서 위치에 이미지 삽입
          this.editor.insertEmbed(range.index, "image", imgUrl);
        } catch (error) {
          console.log("error");
        }
      });
    },
  },
  computed: {
    editor() {
      return this.$refs.myTextEditor.quill;
    },
  },
};
</script>

<style lang="scss" scoped>
.example {
  display: flex;
  flex-direction: column;

  .editor {
    height: 40rem;
    overflow: hidden;
  }

  .output {
    width: 100%;
    height: 20rem;
    margin: 0;
    border: 1px solid #ccc;
    overflow-y: auto;
    resize: vertical;

    &.code {
      padding: 1rem;
      height: 16rem;
    }

    &.ql-snow {
      border-top: none;
      height: 24rem;
    }
  }
}
</style>

 

확인

반응형