vue-element-admin 上傳upload圖片慢問題處理

前言

vue-element-admin自帶上傳圖片組件,在使用的過程中發現上傳速度很慢,尤其是上傳一些大圖需要耗時幾十秒不能忍受。出現這種情況,是因爲upload組件會將圖片上傳到action="https://httpbin.org/post" ,並返回轉換成base64編碼格式的數據。

格式類似:

data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAAIBAQEBAQIBAQECAgICAgQDAgICAgUEBAMEBgUGBgYFBgYGBwkIBgcJBwYGCAsIC.....

而且有可能這個base64編碼比上傳源文件還要大。

這樣做有兩個缺點:

  • 多一步上傳文件到第三方網站(https://httpbin.org/post),並轉碼base64,其中大部分時間在這一步浪費的。
  • 服務端在接收base64編碼內容,還要將其處理成文件進行單獨保存(base64編碼內容太長,通常不會直接存入數據庫),這給服務端帶來不便。

還有一點就這種是必須圖片和表單其他內容一起提交,有的時候上傳和表單其他項分開提交。

接下來講一下如何將圖片單獨上傳到服務的實現步驟:

具體代碼在以下項目裏

github:

https://github.com/guyan0319/go-admin

碼雲(國內):

https://gitee.com/jason0319/go-admin

示例一、解決如下圖所示的上傳和刪除

1、新建文件

vue-element-admin\src\utils\global.js

內容如下

const httphost = 'http://localhost:8090'
export { httphost }

這個是服務端的地址,可以根據需要自己調整。

2、修改上傳組件代碼在SingleImage3.vue

上傳圖片

引入上面定義的服務器地址

import { httphost } from '@/utils/global'

data()增加uploadUrl

data() {
    return {
      tempUrl: '',
      uploadUrl: httphost + '/upload/image',
      dataObj: { token: '', key: '' }
    }
  },

action=``"https://httpbin.org/post" 

修改爲

 :action="uploadUrl"

圖片上傳成功on-success綁定的handleImageSuccess函數增加了res,即服務端返回上傳結果。

修改代碼如下

handleImageSuccess(res, file) {
      if (res.code !== 20000){
        this.$message({
          message: '上傳失敗',
          type: 'error',
          showClose: true
        })
        return false
      }
      this.emitInput(res.data)
    },

服務端返回的json格式爲

{
    "code":20000,
    "data":"http://localhost:8090/showimage?imgname=upload/20200620/tX5vS810l2Fl0K02I0YJLEjLEw9OH7hc.jpg"
}

這裏需要注意el-upload增加

:with-credentials='true'

支持發送 cookie 憑證信息,上傳文件到服務器端需要判斷驗證登錄。

刪除圖片

通過以上修改實現上傳圖片,接下處理上傳文件刪除

文件api/article.js 增加

export function delImage(url) {
  return request({
    url: '',
    method: 'get',
    params: { url },
    baseURL: httphost + '/del/image'
  })
}

修改SingleImage3.vue

//引入delImage
import { delImage } from '@/api/article'
 
 rmImage() {
      delImage(this.value).then(response => {
        if (response.code === 20000){
          this.emitInput('')
          return
        }
        this.$message({
          message: '刪除失敗',
          type: 'error',
          showClose: true
        })
      }).catch(err => {
        console.log(err)
      })
    },

服務端刪除文件返回json

{"code":20000,"data":"success"}

最後貼一下SingleImage3.vue修改後完整的代碼

<template>
  <div class="upload-container">
    <el-upload
      :data="dataObj"
      :multiple="false"
      :show-file-list="false"
      :with-credentials='true'
      :on-success="handleImageSuccess"
      class="image-uploader"
      drag
      :action="uploadUrl"
    >
      <i class="el-icon-upload" />
      <div class="el-upload__text">
        將文件拖到此處,或<em>點擊上傳</em>
      </div>
    </el-upload>
    <div class="image-preview image-app-preview">
      <div v-show="imageUrl.length>1" class="image-preview-wrapper">
        <img :src="imageUrl">
        <div class="image-preview-action">
          <i class="el-icon-delete" @click="rmImage" />
        </div>
      </div>
    </div>
    <div class="image-preview">
      <div v-show="imageUrl.length>1" class="image-preview-wrapper">
        <img :src="imageUrl">
        <div class="image-preview-action">
          <i class="el-icon-delete" @click="rmImage" />
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { getToken } from '@/api/qiniu'
import { delImage } from '@/api/article'
import { httphost } from '@/utils/global'
// import { Cookies } from 'js-cookie'
export default {
  name: 'SingleImageUpload3',
  props: {
    value: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      tempUrl: '',
      uploadUrl: httphost + '/upload/image',
      dataObj: { token: '', key: '' }
    }
  },
  computed: {
    imageUrl() {
      return this.value
    }
  },
  methods: {
    rmImage() {
      delImage(this.value).then(response => {
        if (response.code === 20000){
          this.emitInput('')
          return
        }
        this.$message({
          message: '刪除失敗',
          type: 'error',
          showClose: true
        })
      }).catch(err => {
        console.log(err)
      })
    },
    emitInput(val) {
      this.$emit('input', val)
    },

    handleImageSuccess(res, file) {
      if (res.code !== 20000){
        this.$message({
          message: '上傳失敗',
          type: 'error',
          showClose: true
        })
        return false
      }
      this.emitInput(res.data)
    },
    beforeUpload() {
      const _self = this
      return new Promise((resolve, reject) => {
        getToken().then(response => {
          const key = response.data.qiniu_key
          const token = response.data.qiniu_token
          _self._data.dataObj.token = token
          _self._data.dataObj.key = key
          this.tempUrl = response.data.qiniu_url
          resolve(true)
        }).catch(err => {
          console.log(err)
          reject(false)
        })
      })
    }
  }
}
</script>

<style lang="scss" scoped>
@import "~@/styles/mixin.scss";
.upload-container {
  width: 100%;
  position: relative;
  @include clearfix;
  .image-uploader {
    width: 35%;
    float: left;
  }
  .image-preview {
    width: 200px;
    height: 200px;
    position: relative;
    border: 1px dashed #d9d9d9;
    float: left;
    margin-left: 50px;
    .image-preview-wrapper {
      position: relative;
      width: 100%;
      height: 100%;
      img {
        width: 100%;
        height: 100%;
      }
    }
    .image-preview-action {
      position: absolute;
      width: 100%;
      height: 100%;
      left: 0;
      top: 0;
      cursor: default;
      text-align: center;
      color: #fff;
      opacity: 0;
      font-size: 20px;
      background-color: rgba(0, 0, 0, .5);
      transition: opacity .3s;
      cursor: pointer;
      text-align: center;
      line-height: 200px;
      .el-icon-delete {
        font-size: 36px;
      }
    }
    &:hover {
      .image-preview-action {
        opacity: 1;
      }
    }
  }
  .image-app-preview {
    width: 320px;
    height: 180px;
    position: relative;
    border: 1px dashed #d9d9d9;
    float: left;
    margin-left: 50px;
    .app-fake-conver {
      height: 44px;
      position: absolute;
      width: 100%; // background: rgba(0, 0, 0, .1);
      text-align: center;
      line-height: 64px;
      color: #fff;
    }
  }
}
</style>

示例二、解決如下圖所示的上傳

需要修改vue-element-admin\src\components\Tinymce\components\EditorImage.vue文件,處理方式和示例一差不多,這裏只貼代碼

<template>
  <div class="upload-container">
    <el-button :style="{background:color,borderColor:color}" icon="el-icon-upload" size="mini" type="primary" @click=" dialogVisible=true">
      upload
    </el-button>
    <el-dialog :visible.sync="dialogVisible">
      <el-upload
        :multiple="true"
        :file-list="fileList"
        :show-file-list="true"
        :with-credentials='true'
        :on-remove="handleRemove"
        :on-success="handleSuccess"
        :before-upload="beforeUpload"
        class="editor-slide-upload"
        :action="uploadUrl"
        list-type="picture-card"
      >
        <el-button size="small" type="primary">
          Click upload
        </el-button>
      </el-upload>
      <el-button @click="dialogVisible = false">
        Cancel
      </el-button>
      <el-button type="primary" @click="handleSubmit">
        Confirm
      </el-button>
    </el-dialog>
  </div>
</template>

<script>
// import { getToken } from 'api/qiniu'
import { delImage } from '@/api/article'
import { httphost } from '@/utils/global'
export default {
  name: 'EditorSlideUpload',
  props: {
    color: {
      type: String,
      default: '#1890ff'
    }
  },
  data() {
    return {
      dialogVisible: false,
      uploadUrl: httphost + '/upload/image',
      listObj: {},
      fileList: []
    }
  },
  methods: {
    checkAllSuccess() {
      return Object.keys(this.listObj).every(item => this.listObj[item].hasSuccess)
    },
    handleSubmit() {
      const arr = Object.keys(this.listObj).map(v => this.listObj[v])
      if (!this.checkAllSuccess()) {
        this.$message('Please wait for all images to be uploaded successfully. If there is a network problem, please refresh the page and upload again!')
        return
      }
      this.$emit('successCBK', arr)
      this.listObj = {}
      this.fileList = []
      this.dialogVisible = false
    },
    handleSuccess(response, file) {
      const uid = file.uid
      const objKeyArr = Object.keys(this.listObj)
      for (let i = 0, len = objKeyArr.length; i < len; i++) {
        if (this.listObj[objKeyArr[i]].uid === uid) {
          this.listObj[objKeyArr[i]].url = response.data
          // this.listObj[objKeyArr[i]].url = response.files.file
          this.listObj[objKeyArr[i]].hasSuccess = true
          return
        }
      }
    },
    handleRemove(file) {
      const uid = file.uid
      const objKeyArr = Object.keys(this.listObj)
      for (let i = 0, len = objKeyArr.length; i < len; i++) {
        if (this.listObj[objKeyArr[i]].uid === uid) {
          delImage(this.listObj[objKeyArr[i]].url).then(response => {
            if (response.code !== 20000) {
              this.$message('刪除失敗')
              return
            }
            delete this.listObj[objKeyArr[i]]
          }).catch(err => {
            console.log(err)
          })

          return
        }
      }
    },
    beforeUpload(file) {
      const _self = this
      const _URL = window.URL || window.webkitURL
      const fileName = file.uid
      this.listObj[fileName] = {}
      return new Promise((resolve, reject) => {
        const img = new Image()
        img.src = _URL.createObjectURL(file)
        img.onload = function() {
          _self.listObj[fileName] = { hasSuccess: false, uid: file.uid, width: this.width, height: this.height }
        }
        resolve(true)
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.editor-slide-upload {
  margin-bottom: 20px;
  /deep/ .el-upload--picture-card {
    width: 100%;
  }
}
</style>

至此,vue-element-admin 單獨上傳圖片實現方式就講完了,如有任何問題或建議歡迎提issues

links

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