wangEditor服務器上傳圖片(Vue使用)


這兩天在用wangEditor的時候在上傳圖片的時候遇到一些問題
有些地方也沒有直接貼出源碼只是貼了一些偽代碼,
這里我將我練手的項目demo貼出來,這里只是例舉了我的方案,具體操作建議觀看


基本配置

如下

 editor.customConfig.showLinkImg = false  //關閉網絡路徑圖片方式
 editor.customConfig.uploadImgServer = 'http://localhost:3000/upload' // 上傳圖片的接口地址
 editor.customConfig.uploadFileName = 'file' // formdata中的name屬性

請求頭

還有一個是請求頭,后台在上傳文件的時候需要添加請求頭驗證,此處我這邊需要添加一個Authorization
代碼如下

editor.customConfig.uploadImgHeaders = {
      Authorization: localStorage.getItem('toutoken') // 設置請求頭
    }

開啟debug模式

開啟debug模式可以幫我們定位bug

    editor.customConfig.debug = true // 開啟debug模式

設置監聽函數

 editor.customConfig.uploadImgHooks = {
      // 圖片上傳並返回結果,但圖片插入錯誤時觸發
      fail: function (xhr, editor, result) {
        console.log(result)
      },
      success: function (xhr, editor, result) {
        // 圖片上傳並返回結果,圖片插入成功之后觸發
        console.log(result, 'success')
      }
    }

完整代碼

<template>
  <div>
    <div id="editor" ref="editor">
      <p>
        歡迎使用
        <b>wangEditor</b> 富文本編輯器
      </p>
    </div>
  </div>
</template>

<script>
import Wangeditor from 'wangeditor'
export default {
  mounted () {
    const editor = new Wangeditor(this.$refs.editor)
    editor.customConfig.showLinkImg = false
    editor.customConfig.uploadImgServer = 'http://localhost:3000/upload' // 上傳圖片的接口地址
    editor.customConfig.uploadFileName = 'file' // formdata中的name屬性
    editor.customConfig.debug = true // 開啟debug模式
    editor.customConfig.uploadImgHeaders = {
      Authorization: localStorage.getItem('toutoken') // 設置請求頭
    }
    editor.customConfig.uploadImgHooks = {
      // 圖片上傳並返回結果,但圖片插入錯誤時觸發
      fail: function (xhr, editor, result) {
        console.log(result)
      },
      success: function (xhr, editor, result) {
        // 圖片上傳並返回結果,圖片插入成功之后觸發
        console.log(result, 'success')
      }
    }
    editor.create()
  }
}
</script>

<style lang="less" scoped>
#editor {
  width: 80%;
  margin: 0 auto;
}
</style>

遇到errno=undefined錯誤

在上傳圖片成功,但是卻會觸發fail並顯示errno=undefined的話說明后台放回的字段中沒有errno需要和后台溝通並加上此字段,還有若data有問題則需要與后台溝通,data應該是一個數組,存儲着圖片的值的路徑


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM