Vue Quill-Editor 上傳圖片到服務器(富文本編輯器)

安裝
npm install vue-quill-editor --save //下載Vue-Quill-Editor
npm install quill --save /下載quill(Quill-Editor的賴)

代碼

  <el-form-item label="" sortable label="" autosize>
                <div class="edit_container" autosize>
                            <el-upload
                        accept="image/png,image/jpeg,image/jpg,image/gif"
                                      class="avatar-uploader quill-img"
                                      action="/admin/upEditeFile"    //圖片上傳地址
                                      :show-file-list="false"
                                      :on-success="uploadSuccess"
                                      >
                              </el-upload>
                    <quill-editor    //編輯器
                            style="width:400px"
                            v-model="store.project_desc"
                            ref="myQuillEditor"
                            :options="editorOption"
                            @blur="onEditorBlur($event)" @focus="onEditorFocus($event)"
                            @change="onEditorChange($event)"
                    >

                    </quill-editor>
                </div>
            </el-form-item>
            <script>
            //設置工具欄
    const toolbarOptions = [   
        ['bold', 'italic', 'underline', 'strike'],        
        ['blockquote', 'code-block'],
        [{'list': 'ordered'}, {'list': 'bullet'}],
        [{'script': 'sub'}, {'script': 'super'}],      
        [{'indent': '-1'}, {'indent': '+1'}],          
       // [{'direction': 'rtl'}],
        [{ 'size': ['small', false, 'large', 'huge'] }],
        [{ 'header': [1, 2, 3, 4, 5, 6, false] }],       
        [{'color': []}, {'background': []}],        
       // [{'align': []}],
        ['image','video'],
        ['clean']                                        
    ]
    import { quillEditor } from "vue-quill-editor"; //調用編輯器
    import 'quill/dist/quill.core.css';
    import 'quill/dist/quill.snow.css';
    import 'quill/dist/quill.bubble.css';
    import handleTreeData from '../../utils/handleTreeData'
    export default {
        name: "TopMain",
        components: {
            quillEditor
        },
        data() {
            return {
                store: {},
                roles: 0,
                content:null,
                editorOption: {
                    placeholder: '',
                    theme: 'snow',  // or 'bubble'snow
                    modules: {
                        toolbar: {
                            container: toolbarOptions,  // 工具欄
                            handlers: {
                                'image': function (value) {
                                    if (value) {
                                        // 觸發input框選擇圖片文件
                                        document.querySelector('.quill-img input').click()
                                    } else {
                                        this.quill.format('image', false);
                                    }
                                }
                            }
                        }
                    },
                }

            }
        },
        methods: {
            /* county CollectEdit Page */
            onEditorReady(editor) { // 準備編輯器

            },
            uploadSuccess(res) {  //把已經上傳的圖片顯示回富文本編輯框中
                console.log(res);
                //res返回的格式是{url:"圖片的路徑"},這個是後臺接口返回的
                let quill = this.$refs.myQuillEditor.quill
                quill.focus();
                quill.insertEmbed(quill.getSelection().index, 'image', res);    //在編輯器中顯示上傳的圖片
                console.log(res);

            },
            onEditorBlur(){}, // 失去焦點事件
            onEditorFocus(){}, // 獲得焦點事件
            onEditorChange(){
            }, // 內容改變事件
            escapeStringHTML(str) {
                str = str.replace(/&lt;/g, '<');
                str = str.replace(/&gt;/g, '>');
                return str;
            },
            formSave() {
                this.store.save = true;
                this.$http.post("/admin/county/collectEdit", this.store).then(({data = {}}) => {
                    if (data.code === 200) {
                        this.$notify({
                            title: '提示',
                            message: 'OK',

                            position: 'bottom-right'
                        });
                        let url = this.roles == 1 ? "#/county/store" : "#/county/collect";
                        setTimeout(function () {
                            location.href = url;
                        }, 2000);
                    } else if (data.code === 400) {
                        this.$message("錯誤:" + data.message);
                    }
                }).catch((err) => {
                    this.$message("服務端錯誤" + err);
                })
            },
            //獲取數據
            getMsg() {    
                this.$http.get("/admin/county/collectEdit", {params: {id: this.$route.params.id}}).then(({data = {}}) => {
                    this.store = data.data.store;
                    this.roles = data.data.roles;

                }).catch((err) => {
                    this.$message("錯誤:" + err);
                })
            },
        },
        computed: {
            editor() {
                return this.$refs.myQuillEditor.quill;
            },
        },
        mounted() {
            let content = '';  // 請求後臺返回的內容字符串
            this.str = this.escapeStringHTML(content);
        },
        created() {
            this.getMsg();
        }
    }
</script>

php


    /**
    *富文本編輯器上傳圖片
     */
    public function upEditeFile(Request $request)
    {
        if ($request->isMethod('POST')) {

            $fileCharater = $request->file('file');
            if ($fileCharater->isValid()) {
                $ext = $fileCharater->getClientOriginalExtension();
                //獲取文件的絕對路徑
                $jpg = (string) Image::make($fileCharater)->encode('jpg',90);
                $filename = 'images/'.date('Ymd').'/'.date('YmdHis').rand(100, 999).'.'.$ext;
                Storage::disk('public')->put($filename, $jpg);
                $filename =  \App\Components\Common::upImg($filename);
                $filename =   \App\Components\Common::showImg($filename);
                return $filename;
            }
        }else{
            return \App\Components\Common::fail('編輯失敗',400);
        }
    }

參考原文

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章