md5.js
import SparkMD5 from 'spark-md5'
const DEFAULT_SIZE = 20 * 1024 * 1024
const md5 = (file, chunkSize = DEFAULT_SIZE) => {
return new Promise((resolve, reject) => {
const startMs = new Date().getTime();
let blobSlice =
File.prototype.slice ||
File.prototype.mozSlice ||
File.prototype.webkitSlice;
let chunks = Math.ceil(file.size / chunkSize);
let currentChunk = 0;
let spark = new SparkMD5.ArrayBuffer(); //追加数组缓冲区。
let fileReader = new FileReader(); //读取文件
fileReader.onload = function (e) {
spark.append(e.target.result);
currentChunk++;
if (currentChunk < chunks) {
loadNext();
} else {
const md5 = spark.end(); //完成md5的计算,返回十六进制结果。
console.log('文件md5计算结束,总耗时:', (new Date().getTime() - startMs) / 1000, 's')
resolve(md5);
}
};
fileReader.onerror = function (e) {
reject(e);
};
function loadNext() {
console.log('当前part number:', currentChunk, '总块数:', chunks);
let start = currentChunk * chunkSize;
let end = start + chunkSize;
(end > file.size) && (end = file.size);
fileReader.readAsArrayBuffer(blobSlice.call(file, start, end));
}
loadNext();
});
}
export default md5
videoAdd.vue
<template>
<div class='video-add'>
<a-spin :spinning="butonLoading">
<a-upload v-model:file-list="fileList" name="file" action="/" :customRequest="handleHttpRequest" type="line"
:onRemove="handleRemoveFile" accept=".mp4,.ogg,.flv,.avi,.wmv,.rmvb,.mov" maxCount="1">
<a-button v-if="!showPercent">选择文件</a-button>
<a-tooltip color="#fff" title="若已存在视频,继续上传将会覆盖原有视频" :overlayInnerStyle="{ color: '#000' }">
<i class="iconfont tooltip-icon icon-tishi mr-8"></i>
</a-tooltip>
</a-upload>
<div class="flex f-between mt-20" v-if="datas?.fileName">
<span>{{ datas.fileName }}</span>
<div class="flex">
<a-popconfirm title="确认删除当前视频?" ok-text="确认" cancel-text="取消" @confirm="confirmDel(datas)">
<i class="iconfont icon-shanchu1"></i>
</a-popconfirm>
</div>
</div>
<a-progress v-if="showPercent" :percent="percent" />
<a-space class="flex f-end mt-30">
<a-button @click="() => emit('update:open', false)">取消</a-button>
</a-space>
<CommonModal v-model:open="open" title="使用链接上传文件" width="fit-content" :footer="false">
<videoInfo v-model:open="open" :info="info" @closeModel="closeModal" />
</CommonModal>
</a-spin>
</div>
</template>
<script setup lang='ts'>
import md5 from '@/utils/md5'
import { taskInfo, initTask, preSignUrl, merge } from '@/request/uploadVideo';
import Queue from 'promise-queue-plus';
import axios from "axios";
import { ref, inject, watch } from 'vue'
import videoInfo from './videoInfo.vue';
import { delChapterVideo, getChapterVideo } from "@/request/courseManagement";
import { message } from 'ant-design-vue';
import { cloneDeep } from "lodash-es";
const props = defineProps({
info: {
default: null,
type: Object
}
})
const fileList = ref([])
const emit = defineEmits(['update:open'])
const open = ref(false)
const butonLoading = ref<boolean>(false);
const percent = ref(0)
const datas: any = ref({
fileName: null
});
const videoRef = ref();
let copyData = ref([])
let video = ref()
const closeModal = () => {
open.value = false
changeVisible()
getData()
}
const showPercent = ref(false)
const changeVisible: any = inject("changeVisible") //关闭弹窗
const getData: any = inject("getData")
// 确认删除视频
const confirmDel = data => {
delChapterVideo({ chapterId: data.chapterId, }).then((res: any) => {
if (res.code === 200) {
datas.value = null
message.success('删除成功')
getData()
} else {
message.error(res.msg)
}
})
}
// 获取视频列表
const getVideoNameList = () => {
getChapterVideo({ chapterId: props.info.id, }).then((res: any) => {
if (res.code === 200) {
datas.value = res.data
copyData = cloneDeep(res.data)
} else {
message.error(res.msg)
}
})
}
watch(() => props.info, val => {
if (val) {
getVideoNameList()
}
}, { immediate: true, deep: true })
const getTaskInfo = async (file) => {
let task;
const identifier = await md5(file)
const { code, data, msg } = await taskInfo(identifier, props.info.id)
if (code === 200) {
task = data
if (!task) {
const initTaskData = {
identifier,
fileName: file.name,
totalSize: file.size,
chunkSize: 5 * 1024 * 1024,
chapterId: props.info.id
}
const { code, data, msg } = await initTask(initTaskData)
if (code === 200) {
task = data
} else {
message.error({
title: '文件上传错误',
message: msg
})
}
}
} else {
message.error({
title: '文件上传错误',
message: msg
})
}
return task
}
const handleUpload = (file, taskRecord: any, options) => {
let lastUploadedSize: any = 0; // 上次断点续传时上传的总大小
let uploadedSize = 0 // 已上传的大小
const totalSize = file.size || 0 // 文件总大小
let startMs = new Date().getTime(); // 开始上传的时间
const { exitPartList, chunkSize, chunkNum, fileIdentifier } = taskRecord
// 获取从开始上传到现在的平均速度(byte/s)
const getSpeed = () => {
// 已上传的总大小 - 上次上传的总大小(断点续传)= 本次上传的总大小(byte)
const intervalSize = uploadedSize - lastUploadedSize
const nowMs = new Date().getTime()
// 时间间隔(s)
const intervalTime = (nowMs - startMs) / 1000
return intervalSize / intervalTime
}
const uploadNext = async (partNumber) => {
const start: any = new Number(chunkSize) * (partNumber - 1)
const end = start + new Number(chunkSize)
const blob = file.slice(start, end)
const { code, data, msg } = await preSignUrl({ identifier: fileIdentifier, partNumber: partNumber, chapterId: props.info.id })
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 为已上传的进度增加的字节量
*/
const updateProcess = (increment) => {
increment = new Number(increment)
const { onProgress } = options
console.log('onProgress', onProgress)
let factor = 1000; // 每次增加1000 byte
let from = 0;
// 通过循环一点一点的增加进度
while (from <= increment) {
from += factor
uploadedSize += factor
const percent = Math.round(uploadedSize / totalSize * 100).toFixed(2);
onProgress({ percent: percent })
}
const speed = getSpeed();
const remainingTime = speed != 0 ? Math.ceil((totalSize - uploadedSize) / speed) + 's' : '未知'
console.log('剩余大小:', (totalSize - uploadedSize) / 1024 / 1024, 'mb');
console.log('当前速度:', (speed / 1024 / 1024).toFixed(2), 'mbps');
console.log('预计完成:', remainingTime);
}
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);
}
})
fileUploadChunkQueue[file.uid] = queue
for (let partNumber = 1; partNumber <= chunkNum; partNumber++) {
const exitPart = (exitPartList || []).find(exitPart => exitPart.partNumber == partNumber)
if (exitPart) {
// 分片已上传完成,累计到上传完成的总额中,同时记录一下上次断点上传的大小,用于计算上传速度
lastUploadedSize += new Number(exitPart.size)
updateProcess(exitPart.size)
} else {
queue.push(() => uploadNext(partNumber).then(res => {
// 单片文件上传完成再更新上传进度
updateProcess(res.uploadedSize)
}))
}
}
if (queue.getLength() == 0) {
// 所有分片都上传完,但未合并,直接return出去,进行合并操作
resolve(failArr);
return;
}
queue.start()
})
}
const handleHttpRequest = async (options) => {
const file = options.file
const task = await getTaskInfo(file)
if (task) {
const { finished, path, taskRecord } = task
const { fileIdentifier: identifier } = taskRecord
if (finished) {
fileList.value[0].status = 'finished'
message.success('视频提交成功,后台解析中...')
changeVisible()
await getData()
return path
} else {
const errorList: any = await handleUpload(file, taskRecord, options)
if (errorList.length > 0) {
message.error({
title: '文件上传错误',
message: '部分分片上次失败,请尝试重新上传文件'
})
return;
}
const { code, data, msg } = await merge(identifier, props.info.id)
if (code === 200) {
fileList.value[0].status = 'finished'
message.success('视频提交成功,后台解析中...')
changeVisible()
await getData()
return path
} else {
message.error({
title: '文件上传错误',
message: msg
})
}
}
} else {
message.error({
title: '文件上传错误',
message: '获取上传任务失败'
})
}
}
const fileUploadChunkQueue = ref({}).value
const handleRemoveFile = (uploadFile, uploadFiles) => {
const queueObject = fileUploadChunkQueue[uploadFile.uid]
if (queueObject) {
queueObject.stop()
fileUploadChunkQueue[uploadFile.uid] = undefined
}
}
</script>
<style lang='less' scoped>
.video-add {
min-width: 500px;
.mockvideo {
background-color: #000;
width: 100%;
height: 140px;
display: flex;
justify-content: center;
align-items: center;
.anticon {
color: #fff;
font-size: 1.5rem;
}
}
width: 300px;
.icon-shanchu1 {
color: #FF4D4F;
cursor: pointer;
}
.icon-bianji3 {
color: #08A8FD;
}
}
</style>