优化VUE Element UI的上传插件

这篇具有很好参考价值的文章主要介绍了优化VUE Element UI的上传插件。希望对大家有所帮助。如果存在错误或未考虑完全的地方,请大家不吝赐教,您也可以点击"举报违法"按钮提交疑问。

优化VUE Element UI的上传插件,VUE,vue.js,ui,前端优化VUE Element UI的上传插件,VUE,vue.js,ui,前端

默认ElmentUI的文件列表只有一个删除按钮,我需要加预览、下载、编辑等,就需要优化显示结果。

优化后没用上传进度条,又加了一个进度条效果

代码文章来源地址https://www.toymoban.com/news/detail-701440.html

<template>
  <div>
    <el-upload
        class="upload-demo"
        action="/"
        :file-list="fileList"
        :disabled="isUpLoading"
        :before-upload="beforeUpload"
        :http-request="handleHttpRequest"
        :on-remove="handleRemoveFile"
        :on-progress="handleLoading"
        :on-success="handleUploadSuccess">

        <el-button size="small" :loading="isUpLoading" type="primary">{{this.isUpLoading?"附件上传中...":"点击上传"}} </el-button>
        <div slot="tip" class="el-upload__tip">(建议上传附件大小在5M以内)</div>
    </el-upload>
   <div id="file-list">
     <el-progress v-if="isUpLoading" :percentage="uploadingProgress"></el-progress>
     <div v-for="(file,index) in fileList" :key="file.fileIdentifier" style="display: flex;justify-content: space-between;line-height: 25px;">
          <div>{{index+1}}、{{file.name}} </div>
          <div style="padding-right: 20px;">
            <a href="javascript:void(0)" style="cursor:pointer;" @click="fileOption(file,'down')">下载</a>
            <a href="javascript:void(0)" v-if = "officeFileType.includes(file.wjhz.toLowerCase())" style="margin-left: 10px;cursor:pointer;"  @click="fileOption(file,'show')">查看</a>
            <a href="javascript:void(0)" v-if = "officeFileType.includes(file.wjhz.toLowerCase())" style="margin-left: 10px;cursor: pointer;" @click="fileOption(file,'edit')">编辑</a>
            <a href="javascript:void(0)" style="margin-left: 10px;cursor: pointer;" @click="fileOption(file,'del')">删除</a>
          </div>
     </div>
   </div>
  </div>
</template>

<style lang="scss" scoped>
::v-deep .el-upload-list{
  display: none;
}
</style>



<script>
import md5 from "@/api/file/md5";
import { taskInfo, initTask, preSignUrl, merge, del, getFileList} from '@/api/file/api';
import Queue from 'promise-queue-plus';
import axios from 'axios'
import VXETable from 'vxe-table'
import { changeUserStatus } from '@/api/system/user'


export default {
    name: 'upload-page',
    props: {
		// 文件类型
		fjlxdm: {
			required: true,
			type: String
		},
		// 业务主建
		ywbs: {
			required: true,
			type: String
		},

	},
    created(){
        this.initData();
    },
    data() {
        return {
            fileUploadChunkQueue:{},
            lastUploadedSize:0,// 上次断点续传时上传的总大小
            uploadedSize:0,// 已上传的大小
            totalSize:0,// 文件总大小
            startMs:'',// 开始上传的时间
            taskRecord:{},
            options:{},
            fileList:[],
            officeFileType:['.ppt', '.pptx', '.doc', '.docx', '.xls', '.xlsx','.pdf'],
          isUpLoading:false,
          uploadingProgress:0,
          uploadTime:null,
        }
    },
    methods: {
      handleLoading(event, file, fileList){
        if(this.uploadTime!=null){
          clearInterval(this.uploadTime);
          this.uploadTime=null;
        }
       this.uploadingProgress=parseFloat(event.percent);
      },
      fileOption(file,type){

        if(type=="down"){//下载
          window.open(file.url, "_blank");
          return;
        }
        if(type=="show"){//查看
          const { href } = this.$router.resolve({
            name: 'office',
            query: {
              fjxxbs: file.fjxxbs,
			  viewUrl: file.viewUrl,
              ot: 'detail'
            }
          })
          window.open(href, '_blank')
          return;
        }
        if(type=="edit"){//编辑
          const { href } = this.$router.resolve({
            name: 'office',
            query: {
              fjxxbs: file.fjxxbs,
			  viewUrl: file.viewUrl,
              ot: 'edit'
            }
          })
          window.open(href, '_blank')
          return;
        }
        if(type=="del"){//删除
          this.$confirm(
            '确认删除该附件?',
            "警告",
            {
              confirmButtonText: "确定",
              cancelButtonText: "取消",
              type: "warning",
            }
          )
            .then( () => {
              del(file.fjxxbs).then(ret => {
                const index = this.fileList.findIndex((item) => item.fjxxbs === file.fjxxbs);
                this.fileList.splice(index, 1);

                this.msgSuccess("删除成功");
              });
            })

          return;
        }

      },
        /**
         * 获取附件列表
         */
        initData(){
          this.uploadingProgress=100;
            getFileList(this.ywbs,this.fjlxdm).then(ret => {
                this.fileList = ret.data;
               setTimeout(()=>{
                 this.isUpLoading=false;
               },500);
            })
        },
        /**
         * 获取一个上传任务,没有则初始化一个
         */
        async getTaskInfo(file){
            let task;
            const identifier = await md5(file)
            const { code, data, msg } = await taskInfo(identifier,this.ywbs,this.fjlxdm);
            if (code === 200) {
                task = data
                if (task===undefined) {
                    const initTaskData = {
                        identifier,
                        fileName: file.name,
                        totalSize: file.size,
                        chunkSize: 5 * 1024 * 1024,
                        ywbs:this.ywbs,
                        fjlxdm:this.fjlxdm
                    }
                    const { code, data, msg } = await initTask(initTaskData)
                    if (code === 200) {
                        task = data
                    } else {
                        this.$notify({
                            title:'提示',
                            message: '文件上传错误',
                            type: 'error',
                            duration: 2000
                        })
                    }
                }
            } else {
                this.$notify({
                    title:'提示',
                    message: '文件上传错误',
                    type: 'error',
                    duration: 2000
                })
            }
            return task
        },
        // 获取从开始上传到现在的平均速度(byte/s)
        getSpeed(){
            // 已上传的总大小 - 上次上传的总大小(断点续传)= 本次上传的总大小(byte)
            const intervalSize = this.uploadedSize - this.lastUploadedSize
            const nowMs = new Date().getTime()
            // 时间间隔(s)
            const intervalTime = (nowMs - this.startMs) / 1000
            return intervalSize / intervalTime
        },
        async uploadNext(partNumber){
            const {chunkSize,fileIdentifier} = this.taskRecord;
            const start = new Number(chunkSize) * (partNumber - 1)
            const end = start + new Number(chunkSize)
            const blob = this.options.file.slice(start, end)
            const { code, data, msg } = await preSignUrl({ identifier: fileIdentifier, partNumber: partNumber , ywbs:this.ywbs , fjlxdm:this.fjlxdm} )
            if (code === 200 && data) {
                await axios.request({
                    url: data,
                    method: 'PUT',
                    data: blob,
                    headers: {'Content-Type': 'application/octet-stream'}
                })
                return Promise.resolve({ partNumber: partNumber, uploadedSize: blob.size })
            }
            return Promise.reject(`分片${partNumber}, 获取上传地址失败`)
        },

        /**
         * 更新上传进度
         * @param increment 为已上传的进度增加的字节量
         */
        updateProcess(increment){

            increment = new Number(increment)
            const { onProgress } = this.options
            let factor = 1000; // 每次增加1000 byte
            let from = 0;
            // 通过循环一点一点的增加进度
            while (from <= increment) {
                from += factor
                this.uploadedSize += factor
                const percent = Math.round(this.uploadedSize / this.totalSize * 100).toFixed(2);

                onProgress({percent: percent})
            }

            const speed = this.getSpeed();
            const remainingTime = speed != 0 ? Math.ceil((this.totalSize - this.uploadedSize) / speed) + 's' : '未知'
            console.log('剩余大小:', (this.totalSize - this.uploadedSize) / 1024 / 1024, 'mb');
            console.log('当前速度:', (speed / 1024 / 1024).toFixed(2), 'mbps');
            console.log('预计完成:', remainingTime);
        },

        handleUpload(file, taskRecord){

            this.lastUploadedSize = 0; // 上次断点续传时上传的总大小
            this.uploadedSize = 0 // 已上传的大小
            this.totalSize = file.size || 0 // 文件总大小
            this.startMs = new Date().getTime(); // 开始上传的时间
            this.taskRecord = taskRecord;

            const { exitPartList, chunkNum} = taskRecord

            return new Promise(resolve => {
                const failArr = [];
                const queue = Queue(5, {
                    "retry": 3,               //Number of retries
                    "retryIsJump": false,     //retry now?
                    "workReject": function(reason,queue){
                        failArr.push(reason)
                    },
                    "queueEnd": function(queue){
                        resolve(failArr);
                    }
                })

                this.fileUploadChunkQueue[file.uid] = queue
                for (let partNumber = 1; partNumber <= chunkNum; partNumber++) {
                    const exitPart = (exitPartList || []).find(exitPart => exitPart.partNumber == partNumber)
                    if (exitPart) {
                        // 分片已上传完成,累计到上传完成的总额中,同时记录一下上次断点上传的大小,用于计算上传速度
                        this.lastUploadedSize += new Number(exitPart.size)
                        this.updateProcess(exitPart.size)
                    } else {
                        queue.push(() => this.uploadNext(partNumber).then(res => {
                            // 单片文件上传完成再更新上传进度
                            this.updateProcess(res.uploadedSize)
                        }))
                    }
                }
                if (queue.getLength() == 0) {
                    // 所有分片都上传完,但未合并,直接return出去,进行合并操作
                    resolve(failArr);
                    return;
                }
                queue.start()
            })
        },
        async handleHttpRequest(options){

            this.options = options;
            const file = options.file
            const task = await this.getTaskInfo(file)
            const that = this;

            if (task) {
                const { finished, path, taskRecord } = task
                const {fileIdentifier,fjxxbs } = taskRecord
                if (finished) {
                    return {fileIdentifier,fjxxbs}
                } else {
                    const errorList = await this.handleUpload(file, taskRecord)
                    if (errorList.length > 0) {
                        this.$notify({
                            title:'文件上传错误',
                            message: '部分分片上传失败,请尝试重新上传文件',
                            type: 'error',
                            duration: 2000
                        })
                        return;
                    }
                    const { code, data, msg } = await merge(fileIdentifier,that.ywbs,that.fjlxdm)
                    if (code === 200) {
                        return {fileIdentifier,fjxxbs};
                    } else {
                        this.$notify({
                            title:'提示',
                            message: '文件上传错误',
                            type: 'error',
                            duration: 2000
                        })
                    }
                }
            } else {

                this.$notify({
                    title:'文件上传错误',
                    message: '获取上传任务失败',
                    type: 'error',
                    duration: 2000
                })
            }
        },
        /**
         * 重复上传
         * @param {} file
         */
        beforeUpload(file){
            return new Promise((resolve, reject) => {
                md5(file).then(result => {
                    const index = this.fileList.findIndex((item) => item.fileIdentifier === result);
                    if(index==-1){
                      this.isUpLoading=true;
                      this.uploadingProgress=0;
                      this.uploadTime=setInterval(()=>{
                        this.uploadingProgress+=1;
                      },500)
                        return resolve(true);
                    }else{
                        return reject(false);
                    }
                })
            });
        },
        handleRemoveFile(uploadFile, uploadFiles){
            const queueObject = this.fileUploadChunkQueue[uploadFile.uid]
            if (queueObject) {
                queueObject.stop()
                this.fileUploadChunkQueue[uploadFile.uid] = undefined;
            }

            if(uploadFile.fjxxbs != undefined){
                del(uploadFile.fjxxbs).then(ret => {
                    const index = this.fileList.findIndex((item) => item.fjxxbs === uploadFile.fjxxbs);
                    this.fileList.splice(index, 1);
                })
            }

        },
        /**
         * 上传成功
         */
        handleUploadSuccess(res, file, fileList) {
            // file.fileIdentifier = res.fileIdentifier;
            // file.fjxxbs = res.fjxxbs;
            // this.fileList.push(file);

          this.initData();
        }
    }
}

</script>

到了这里,关于优化VUE Element UI的上传插件的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请点击违法举报进行投诉反馈,一经查实,立即删除!

领支付宝红包 赞助服务器费用

相关文章

  • Cron在前端的使用,vue与element ui的vue-cron插件的使用及将定时任务cron表达式解析成中文

    执行下面npm命令: npm install vue-cron --save 在想使用cron的vue页面引入以下: import VueCron from ‘vue-cron’ import Vue from ‘vue’ Vue.use(VueCron) 运行 在vue页面“style scoped”中通过控制样式去掉秒年 #changeContab /deep/ #tab-0 { display: none; } #changeContab /deep/ #tab-5 { display: none; } 简易的工具类 可根

    2024年02月11日
    浏览(42)
  • Vue上传图片功能【element ui】

    路径那里是axios请求根路径和接口文档里面后端给的路径拼接的 只要看到这个就证明这张图片并没有上传成功 我已经通过axios的request拦截器为每一个请求都挂载了一个Authorization也就是token,挂载了这个也就说明每一个axios请求都会追加一个token 但是为什么配置了token还是显示

    2024年02月12日
    浏览(43)
  • vue2+element ui 上传文件

    完全基于elementui组件封装的上传组件 ,后期继续优化 父组件使用 1、引入组件

    2024年02月04日
    浏览(36)
  • Element-ui配合vue上传图片

    这里为大家介绍饿了吗ui配合vue封装一个图片上传的组件  首先大家先看一个饿了吗ui文档的各个钩子函数的介绍! on-preview这个属性我们一般用来预览图片时使用 on-remove这个属性时文件被删除时执行 一般我们在这里面进行数组的筛选 让它保证为最新数组 on-change当文件被选择

    2024年02月09日
    浏览(59)
  • vue+element ui 实现文件上传下载

    2024年02月14日
    浏览(37)
  • 基于vue+Element UI的文件上传(可拖拽上传)

    drag: 支持拖拽上传 action:必选参数,上传的地址 ref:这里主要是用于文件上传完成后清除文件的 on-remove:文件列表移除文件时的钩子 auto-upload:是否在选取文件后立即进行上传 on-change:文件状态改变时的钩子,添加文件、上传成功和上传失败时都会被调用 注:这里使用的

    2023年04月08日
    浏览(33)
  • ​Vue + Element UI前端篇(二):Vue + Element 案例 ​

    打开 Visual Studio Code,File -- add Folder to Workspace,导入我们的项目。 安装依赖 Element 是国内饿了么公司提供的一套开源前端框架,简洁优雅,提供了 vue、react、angular 等多个版本,我们这里使用 vue 版本来搭建我们的界面。 访问:http://element-cn.eleme.io/#/zh-CN/component/installation ,官

    2024年02月09日
    浏览(30)
  • Vue element ui + AmazonS3上传文件功能

    一、在上传之前,需要先获取到AWS的S3服务的Access key ID和Secret access key 二、代码代码: 别忘记安装AWS.S3!! 三、如果上传失败,报此错误:ETagMissing No access to ETag property on response. Check CORS configuration to expose ETag header. 解决方案: 找到配置的存储桶——权限——跨源资源共享

    2024年02月16日
    浏览(32)
  • 基于vue+element-ui实现上传进度条

    目录 基于el-upload组件实现进度条的编写 后台进度前台进度条显示 基于el-upload组件实现进度条的编写 ①编写文件上传时的钩子函数 ②监听进度百分比 后台进度前台进度条显示 参考文章: 后台进度前台显示进度条_weixin_30646505的博客-CSDN博客 后端思路: ①创建一个类,封装进

    2023年04月08日
    浏览(34)
  • vue+element ui 文件上传之文件缩略图缩略图

    文件缩略图按官方文档说的是使用  scoped-slot  去设置缩略图模版。且需要上传的是图片,因为有预览等功能,如果上传的不是图片,会显示不出来。 这里设置了图片的格式等,用户在选择的时候,会自动校准图片格式,官方文档中提供了before-upload方法,可以防止用户在选择

    2024年02月11日
    浏览(58)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

请作者喝杯咖啡吧~博客赞助

支付宝扫一扫领取红包,优惠每天领

二维码1

领取红包

二维码2

领红包