首页 > 其他分享 >vue-element-admin 上传图片慢问题处理

vue-element-admin 上传图片慢问题处理

时间:2023-06-16 10:14:03浏览次数:41  
标签:vue return admin data image element listObj const 上传

vue-element-admin自带上传图片组件,在使用的过程中发现上传速度很慢,尤其是上传一些大图需要耗时几十秒不能忍受。出现这种情况,是因为upload组件会将图片上传到action="https://httpbin.org/post" ,并返回转换成base64编码格式的数据。

格式类似:

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

而且有可能这个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,return,admin,data,image,element,listObj,const,上传
From: https://www.cnblogs.com/minch/p/17484854.html

相关文章

  • 3d翻转动画 vue3 ts
    <template><section><divclass="flip-container"><divclass="cards":class="{flipped:isFlipped}"><divclass="front"></div><......
  • vue之computed
    对Vuecomputed的理解一、什么是computedVue的computed属性是一种计算属性,它的值是根据其他属性计算而来的。Vue会自动追踪computed属性所依赖的属性,并在这些属性发生变化时重新计算computed属性的值。computed属性的实现原理是使用了Vue的响应式系统。当一个computed属性被访......
  • vue的自定义指令
    自定义指令 含义vue官方提供了v-text,v-bind,v-for,v-model,v-if等常用指令,除此之外vue还允许开发者自定义指令。自定义指令分为两类:私有自定义指令全局自定义指令注意事项自定义指令使用时需要添加v-前缀指令名如果是多个单词,要使用kebab-case短横线命......
  • createelement的用法(转载)
    document.createElement()是在对象中创建一个对象,要与appendChild()或insertBefore()方法联合使用。其中,appendChild()方法在节点的子节点列表末添加新的子节点。insertBefore()方法在节点的子节点列表任意位置插入新的节点。​下面,举例说明document.createElement()的用......
  • Vue项目入门实战(07)-想让你的Vue页面更炫酷?来学习样式绑定吧
    1class的对象绑定1.1需求现在要实现点击div区域里的helloworld文本时,文本变成红色。1.2实现<!DOCTYPEhtml><htmllang="en"><head><metacharset="UTF-8"><title>Vue中的样式绑定</title><scriptsrc="../vue.js&q......
  • Vue3 —— 商城项目
    create-vuecreate-vue是Vue官方新的脚手架工具,底层切换到了vite(下一代前端工具链),为开发提供极速响应。执行如下命令,这一指令将会安装并执行create-vuenpminitvue@latest无论您之前是否安装过create-vue,执行npminitvue@latest命令都会创建一个新的Vue项目。这个命令会......
  • vue时间处理
    vue时间处理https://blog.csdn.net/xc9711/article/details/123347629前言记录vue对时间的处理String与时间戳、时间互转计算时间差设置时间格式:YYYY-MM-DDHH:mm:ss年月日时分秒形式以及HH:mm:ss时分秒形式时间说明在此申明以下使用的时间相关的属性startTime:......
  • Vue项目打包部署上线时devServer.proxy代理失效如何解决?使用nginx的proxy_pass 代理跨
    Vue项目打包部署上线时devServer.proxy代理失效如何解决?使用proxy_pass代理跨域转发前言本篇文章用于记录项目前端部署上线遇到的问题,包含对问题的思考、解决思路,以及从中获得的收获。正确的部署流程我也写了一篇文章,供大家参考使用宝塔将Vue2+Nodejs全栈项目打包部署到腾讯云服......
  • vue学习记录 4
    本地服务器配置apache安装学习参考网址:(官网下载apache包的时候可能会疯狂断开链接)教程里没说,但是要管理员身份操作cmd。https://blog.csdn.net/qqhruchen/article/details/127457889?spm=1001.2101.3001.6661.1&utm_medium=distribute.pc_relevant_t0.none-task-blog-2%7Edefaul......
  • vue封装公共组件库并发布到npm库
    利用的原理:vue框架提供的api:Vue.use(plugin),我们把封装好组件的项目打包成vue库,并提供install方法,然后发布到npm中。Vue.use(plugin)的时候会自动执行插件中的install方法。 一、组件库代码目录调整1.根目录创建packages文件夹2.在packages文件夹中新增components文......