国产 无码 综合区,色欲AV无码国产永久播放,无码天堂亚洲国产AV,国产日韩欧美女同一区二区

優(yōu)化VUE Element UI的上傳插件

這篇具有很好參考價值的文章主要介紹了優(yōu)化VUE Element UI的上傳插件。希望對大家有所幫助。如果存在錯誤或未考慮完全的地方,請大家不吝賜教,您也可以點擊"舉報違法"按鈕提交疑問。

優(yōu)化VUE Element UI的上傳插件,VUE,vue.js,ui,前端優(yōu)化VUE Element UI的上傳插件,VUE,vue.js,ui,前端

默認(rèn)ElmentUI的文件列表只有一個刪除按鈕,我需要加預(yù)覽、下載、編輯等,就需要優(yōu)化顯示結(jié)果。

優(yōu)化后沒用上傳進度條,又加了一個進度條效果

代碼文章來源地址http://www.zghlxwxcb.cn/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以內(nèi))</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
		},
		// 業(yè)務(wù)主建
		ywbs: {
			required: true,
			type: String
		},

	},
    created(){
        this.initData();
    },
    data() {
        return {
            fileUploadChunkQueue:{},
            lastUploadedSize:0,// 上次斷點續(xù)傳時上傳的總大小
            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(
            '確認(rèn)刪除該附件?',
            "警告",
            {
              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);
            })
        },
        /**
         * 獲取一個上傳任務(wù),沒有則初始化一個
         */
        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
        },
        // 獲取從開始上傳到現(xiàn)在的平均速度(byte/s)
        getSpeed(){
            // 已上傳的總大小 - 上次上傳的總大?。〝帱c續(xù)傳)= 本次上傳的總大小(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 為已上傳的進度增加的字節(jié)量
         */
        updateProcess(increment){

            increment = new Number(increment)
            const { onProgress } = this.options
            let factor = 1000; // 每次增加1000 byte
            let from = 0;
            // 通過循環(huán)一點一點的增加進度
            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('當(dāng)前速度:', (speed / 1024 / 1024).toFixed(2), 'mbps');
            console.log('預(yù)計完成:', remainingTime);
        },

        handleUpload(file, taskRecord){

            this.lastUploadedSize = 0; // 上次斷點續(xù)傳時上傳的總大小
            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: '獲取上傳任務(wù)失敗',
                    type: 'error',
                    duration: 2000
                })
            }
        },
        /**
         * 重復(fù)上傳
         * @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>

到了這里,關(guān)于優(yōu)化VUE Element UI的上傳插件的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!

本文來自互聯(lián)網(wǎng)用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務(wù),不擁有所有權(quán),不承擔(dān)相關(guān)法律責(zé)任。如若轉(zhuǎn)載,請注明出處: 如若內(nèi)容造成侵權(quán)/違法違規(guī)/事實不符,請點擊違法舉報進行投訴反饋,一經(jīng)查實,立即刪除!

領(lǐng)支付寶紅包贊助服務(wù)器費用

相關(guān)文章

  • Cron在前端的使用,vue與element ui的vue-cron插件的使用及將定時任務(wù)cron表達(dá)式解析成中文

    Cron在前端的使用,vue與element ui的vue-cron插件的使用及將定時任務(wù)cron表達(dá)式解析成中文

    執(zhí)行下面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日
    瀏覽(58)
  • Vue上傳圖片功能【element ui】

    Vue上傳圖片功能【element ui】

    路徑那里是axios請求根路徑和接口文檔里面后端給的路徑拼接的 只要看到這個就證明這張圖片并沒有上傳成功 我已經(jīng)通過axios的request攔截器為每一個請求都掛載了一個Authorization也就是token,掛載了這個也就說明每一個axios請求都會追加一個token 但是為什么配置了token還是顯示

    2024年02月12日
    瀏覽(36)
  • vue2+element ui 上傳文件

    完全基于elementui組件封裝的上傳組件 ,后期繼續(xù)優(yōu)化 父組件使用 1、引入組件

    2024年02月04日
    瀏覽(29)
  • Element-ui配合vue上傳圖片

    Element-ui配合vue上傳圖片

    這里為大家介紹餓了嗎ui配合vue封裝一個圖片上傳的組件? 首先大家先看一個餓了嗎ui文檔的各個鉤子函數(shù)的介紹! on-preview這個屬性我們一般用來預(yù)覽圖片時使用 on-remove這個屬性時文件被刪除時執(zhí)行 一般我們在這里面進行數(shù)組的篩選 讓它保證為最新數(shù)組 on-change當(dāng)文件被選擇

    2024年02月09日
    瀏覽(30)
  • 基于vue+Element UI的文件上傳(可拖拽上傳)

    基于vue+Element UI的文件上傳(可拖拽上傳)

    drag: 支持拖拽上傳 action:必選參數(shù),上傳的地址 ref:這里主要是用于文件上傳完成后清除文件的 on-remove:文件列表移除文件時的鉤子 auto-upload:是否在選取文件后立即進行上傳 on-change:文件狀態(tài)改變時的鉤子,添加文件、上傳成功和上傳失敗時都會被調(diào)用 注:這里使用的

    2023年04月08日
    瀏覽(30)
  • ?Vue + Element UI前端篇(二):Vue + Element 案例 ?

    ?Vue + Element UI前端篇(二):Vue + Element 案例 ?

    打開 Visual Studio Code,F(xiàn)ile -- add Folder to Workspace,導(dǎo)入我們的項目。 安裝依賴 Element 是國內(nèi)餓了么公司提供的一套開源前端框架,簡潔優(yōu)雅,提供了 vue、react、angular 等多個版本,我們這里使用 vue 版本來搭建我們的界面。 訪問:http://element-cn.eleme.io/#/zh-CN/component/installation?,官

    2024年02月09日
    瀏覽(25)
  • 基于vue+element-ui實現(xiàn)上傳進度條

    基于vue+element-ui實現(xiàn)上傳進度條

    目錄 基于el-upload組件實現(xiàn)進度條的編寫 后臺進度前臺進度條顯示 基于el-upload組件實現(xiàn)進度條的編寫 ①編寫文件上傳時的鉤子函數(shù) ②監(jiān)聽進度百分比 后臺進度前臺進度條顯示 參考文章: 后臺進度前臺顯示進度條_weixin_30646505的博客-CSDN博客 后端思路: ①創(chuàng)建一個類,封裝進

    2023年04月08日
    瀏覽(23)
  • Vue element ui + AmazonS3上傳文件功能

    一、在上傳之前,需要先獲取到AWS的S3服務(wù)的Access key ID和Secret access key 二、代碼代碼: 別忘記安裝AWS.S3??! 三、如果上傳失敗,報此錯誤:ETagMissing No access to ETag property on response. Check CORS configuration to expose ETag header. 解決方案: 找到配置的存儲桶——權(quán)限——跨源資源共享

    2024年02月16日
    瀏覽(17)
  • vue+element ui 關(guān)于表格中多行增加上傳文件操作

    先創(chuàng)建一個表格標(biāo)簽,表格中需要先寫上上傳文件的組件 在data中定義一個表格數(shù)組,數(shù)組中的fileIdList是我需要存儲的信息,可自行參考 表格多行上傳的難點在于,需要把上傳的文件和表格中的行一一對應(yīng),所以在handleSuccess和handleRemove方法中多傳入了一個scope,scope參數(shù)是自

    2024年02月14日
    瀏覽(30)

覺得文章有用就打賞一下文章作者

支付寶掃一掃打賞

博客贊助

微信掃一掃打賞

請作者喝杯咖啡吧~博客贊助

支付寶掃一掃領(lǐng)取紅包,優(yōu)惠每天領(lǐng)

二維碼1

領(lǐng)取紅包

二維碼2

領(lǐng)紅包