programing

Quill 편집기 + VueJS2 이미지 업로드:URL에 대한 Base64 이미지

prostudy 2022. 4. 22. 20:53
반응형

Quill 편집기 + VueJS2 이미지 업로드:URL에 대한 Base64 이미지

여기서 편집기 사용: https://github.com/surmon-china/vue-quill-editor

Quill 편집기에서 MySQL 데이터베이스에 이미지를 저장하려고 하는데 base64의 큰 이미지가 너무 길어서 삽입할 수 없다.

서버에 이미지를 자동 업로드하고 서버가 이미지 URL을 반환하도록 사용자 지정 이미지 핸들러를 쓰려고 했는데, 이제 막혔다.

현재 HTML:

<quill-editor v-model="content"
    :options="editorOption"
    @onEditorBlur($event)"
    @onEditorFocus($event)"
    @onEditorReady($event)"
    @onEditorChange($event)">
</quill-editor>

다음과 같은 편집기에 이미지 처리기 추가:

onEditorReady(editor) {
    editor.getModule('toolbar').addHandler('image', this.imageHandler);
    console.log('editor ready!', editor);
},

그리고 나만의 핸들러:

imageHandler(image, callback){
    console.log(image); // Always true
    console.log(callback); // Always undefined

    // Should get image in here somehow..
    var sendData = {
        image: 'SomethingShouldBeInHere',
    };

    // Send image to server, 
    //  Server will return link to image
    axios.put('/testImageUpload', sendData)
    .then(function(cbData) {
        // In here should add image tag to editor somehow..

    })
    .catch(function (error) {
        console.log(error);
    });
},

난 이렇게 해봤어:사용자 지정 이미지 처리기에 대한 지원 추가 그러나 이미지가 항상 참이고 콜백(callback)이 정의되지 않기 때문에 작동하지 않는다.

이것도 먹어봤어:퀼 데모 첫 번째 링크에는 동일한 문제가 있다.

현재 서버가 "http://localhost/images/php.jpg"를 반환하도록 하드 코딩됨

가능하면 라이브러리(jQuery, dropzone 등)를 사용하지 않을 것이다.

이미지가 EditorChange()에 삽입되어 있는지 확인하고 서버에 요청을 보내 URL을 가져오고 편집기에서 이 base64를 검색하여 URL로 교체하면 될 것 같았는데, 맞지 않는 것 같다.

다음과 같은 옵션에서 핸들러 설정

editorOption: {
  modules: {
   toolbar: {
    container: [['image'], ...],
    handlers: {
     'image': function(){
      document.getElementById('getFile').click()
     }
    }
   } 
  }
}


methods: {
  uploadFunction(e){
  
    //you can get images data in e.target.files
    //an single example for using formData to post to server
    
    
    var form = new FormData()
    form.append('file[]', e.target.files[0])
    
    //do your post
    
    
  }
}
<template>
  <quill-editor v-model="content"
            :options="editorOption"
            @change="oneEditorChange($event)">
  </quill-editor>
  <input type="file" id="getFile" @change="uploadFunction($event)" />
</template>

이건 내 소스 코드야...

//Template
<input type="file" @change="uploadFunction" id="file" hidden>

<quill-editor 
      v-model="model" 
      :options="editorOption" 
      ref="quillEdit">
</quill-editor>

그리고 대본

 //script
    import "quill/dist/quill.core.css";
    import "quill/dist/quill.snow.css";
    import "quill/dist/quill.bubble.css";
    import Quill from "quill";
    import { quillEditor } from "vue-quill-editor";
    import ImageResize from "quill-image-resize-module";
    import axios from '~/plugins/axios'

    export default {
      data() {
        model: '',
        selectedFile : '',
        editorOption: {
            // some quill options
            modules: {
              toolbar: {
                container: [["bold", "image"]],
                handlers: {
                  image: function() {
                    document.getElementById('file').click()
                  }
                }
              },
              imageResize: {
                modules: ["Resize", "DisplaySize", "Toolbar"]
              }
            }
          },
       },
       methods: {
        uploadFunction(e){
             this.selectedFile = e.target.files[0];

          var form = new FormData();
          form.append("file", this.selectedFile);
          form.append("name", this.selectedFile.name);

            //upload image to server
            axios.post('media-save', form,{
             'headers': {
                 'Content-Type': "multipart/form-data"
              }
             })
            .then(r => {
              console.log('success')

              //this code to set your position cursor
const range = this.$refs.quillEdit.quill.getSelection()
//this code to set image on your server to quill editor
              this.$refs.quillEdit.quill.insertEmbed(range.index , 'image', `http://your.api/${r}`)
            })
            .catch(e => {
              console.log('error')
         }
       }
    }

참조URL: https://stackoverflow.com/questions/43857373/quill-editor-vuejs2-image-upload-base64-image-to-url

반응형