| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809 |
- <template>
- <div>
- <a-upload-dragger
- :file-list="fileList"
- :before-upload="beforeUpload"
- @change="handleChange"
- :show-upload-list="false"
- :customRequest="customRequest"
- :multiple="false"
- :drag="true"
- :progress="progress"
- >
- <div style="padding: 40px; text-align: center">
- <span class="text"> 点击上传或将文件拖拽至此区域上传 </span>
- <p class="text">按住Ctrl可同时多选,支持上传PPT/excel/pdf/mp4/zip/rar,等单个文件不能超过2G</p>
- </div>
- </a-upload-dragger>
- <!-- <div style="margin-bottom: 20px">
- <a-button v-if="uploadFileList.length > 0" type="primary" @click="uploadFilesList">上传</a-button>
- </div> -->
- <div v-for="(item, index) in uploadFileList" :key="index">
- <div style="padding: 10px">
- <div style="display: flex; width: 100%; align-items: center; justify-content: space-between">
- <div>
- <span>{{ item.name.length > 20 ? item.name.slice(0, 20) + '...' + item.fileSuffix : item.name }}</span>
- </div>
- <div>
- <span v-if="item.time != ''" style="display: block; color: blue">{{ item.time }}</span>
- </div>
- <div>
- <div>
- <span
- v-if="item.percents == 0 || item.percents == 100"
- style="color: red; cursor: pointer; margin-left: 10px"
- @click="handlerRemoveItem(index)"
- >删除</span
- >
- <span
- v-if="
- item.percents >= 0 &&
- item.percents < 100 &&
- (pauseFlags[item.md5] == false || pauseFlags[item.md5] == undefined)
- "
- style="color: blue; cursor: pointer; margin-left: 10px"
- @click="pauseUpload(index)"
- >暂停</span
- >
- <span
- v-if="item.percents >= 0 && item.percents < 100 && pauseFlags[item.md5] == true"
- style="color: green; cursor: pointer; margin-left: 10px"
- @click="resumeUpload(index)"
- >恢复</span
- >
- </div>
- </div>
- </div>
- <a-progress :percent="item.percents" />
- </div>
- </div>
- <!-- <div> -->
- <!-- <el-progress :text-inside="true" :stroke-width="20" :percentage="successfulChunkPercents" status="success" /> -->
- <!-- <a-progress :percent="successfulChunkPercents" /> -->
- <!-- </div> -->
- <!-- 已上传列表-->
- <!-- <el-table :data="uploadList" border style="width: 100%">
- <el-table-column fixed prop="id.date" label="日期" width="150"> </el-table-column>
- <el-table-column prop="url" label="下载地址"> </el-table-column>
- <el-table-column label="操作">
- <template #default="scope">
- <el-button link type="primary" size="small" @click.prevent="deleteFile(scope.row.url)"> 删除 </el-button>
- <el-button link type="primary" size="small" @click.prevent="downloadFile(scope.row.url)"> 下载 </el-button>
- </template>
- </el-table-column>
- </el-table> -->
- </div>
- </template>
- <script setup>
- import { ref, onMounted } from 'vue'
- import axios from 'axios'
- import SparkMD5 from 'spark-md5'
- import tool from '@/utils/tool'
- import { message } from 'ant-design-vue'
- import sysConfig from '@/config/index'
- const pauseFlags = ref({}) // 控制每个文件是否暂停 { md5: true/false }
- const uploadingTasks = ref({}) // 正在上传的任务 { md5: true }
- //当前选中的文件
- const currentFile = ref(null)
- const chunkSize = ref(5 * 1024 * 1024)
- const uploadedSize = ref(0) // 已上传文件大小(字节)
- const chunkCount = ref(0)
- const chunksUploaded = ref(0)
- const fileMd5 = ref('') //
- const emit = defineEmits(['onUpLoading', 'onSuccess'])
- const progress = {
- strokeColor: {
- '0%': '#108ee9',
- '100%': '#87d068'
- },
- strokeWidth: 3,
- format: (percent) => `${parseFloat(percent.toFixed(2))}%`,
- class: 'test'
- }
- const allChunks = ref(0) // 文件的md5值
- const successfulChunkPercents = ref(0) // 上传成功的分片百分比
- const fileSuffix = ref('') // 文件后缀
- const chunkList = ref([]) // 文件后缀
- const uploadList = ref([]) // 文件后缀
- const fileList = ref([]) // 文件后缀
- const uploadFileList = ref([]) // 文件后缀
- const uploadChunks = ref([]) // 文件后缀
- const upLoadTag = ref(false) // 文件的md5值
- const startTime = ref(0) // 开始时间戳(毫秒
- const totalSize = ref(0) // 开始时间戳(毫秒
- const props = defineProps({
- uploadCount: {
- type: Number,
- default: () => 10
- }
- })
- const handlerRemoveItem = (index) => {
- const item = uploadFileList.value[index]
- if (item && item.md5) {
- delete pauseFlags.value[item.md5] // 清理暂停标志
- }
- uploadFileList.value.splice(index, 1)
- emit('onSuccess', uploadFileList.value)
- }
- const pauseUpload = (index) => {
- const item = uploadFileList.value[index]
- if (item && item.md5) {
- pauseFlags.value[item.md5] = true
- uploadingTasks.value[item.md5] = false
- }
- }
- const resumeUpload = (index) => {
- const item = uploadFileList.value[index]
- if (!item || !item.md5) return
- pauseFlags.value[item.md5] = false
- // 如果当前上传任务小于 2,则开始上传
- const activeTasks = Object.keys(uploadingTasks.value).filter((key) => uploadingTasks.value[key])
- if (activeTasks.length < 2) {
- uploadingTasks.value[item.md5] = true
- // uploadSingleFile(item)
- } else {
- pauseFlags.value[item.md5] = true
- }
- }
- const calculateFileMD5 = (file) => {
- return new Promise((resolve, reject) => {
- const reader = new FileReader()
- const spark = new SparkMD5.ArrayBuffer()
- reader.onload = (e) => {
- spark.append(e.target.result)
- const md5 = spark.end()
- resolve(md5)
- }
- reader.onerror = () => reject(new Error('文件读取失败'))
- reader.readAsArrayBuffer(file)
- })
- }
- const updateProgress = (chunkSize) => {
- uploadedSize.value += chunkSize
- const percent = Math.round((uploadedSize.value / totalSize.value) * 100)
- console.log(`上传进度: ${percent}%`)
- }
- const calculateSpeed = (startTime, uploadedSize) => {
- const currentTime = new Date().getTime()
- const timeElapsed = (currentTime - startTime) / 1000 // 单位:秒
- if (timeElapsed > 0) {
- const speed = uploadedSize / timeElapsed // 单位:字节/秒
- return speed
- }
- return 0
- }
- const estimateRemainingTime = (startTime, uploadedSize, totalSize) => {
- console.log('疑问', ' 总的 ', totalSize, ' 变化的 ', uploadedSize)
- const remainingSize = totalSize - uploadedSize // 剩余文件大小
- const speed = calculateSpeed(startTime, uploadedSize) // 平均上传速度(字节/秒)
- if (speed > 0) {
- const remainingTimeSeconds = remainingSize / speed // 剩余时间(秒)
- return remainingTimeSeconds
- }
- return Infinity // 如果上传速度为 0,则无法估算
- }
- const formatTime = (seconds) => {
- const minutes = Math.floor(seconds / 60)
- const secs = Math.floor(seconds % 60)
- if (minutes == 0 && secs == 0) {
- return ''
- }
- return `${minutes} 分 ${secs} 秒`
- }
- // 异步方法:选择文件时触发 ============
- const handleFileChange = async (file) => {
- // const reader = new FileReader()
- // const spark = new SparkMD5.ArrayBuffer()
- // console.log("读取文件",file.raw)
- // reader.readAsArrayBuffer(file.raw) // 异步读取文件内容
- // const fileContent = await new Promise((resolve, reject) => {
- // reader.onload = (event) => {
- // console.log('开始读取文件了...', event, reader.result)
- // spark.append(event.target.result)
- // resolve(spark.end())
- // }
- // reader.onerror = (error) => {
- // console.log('读取文件时发生错误...', error)
- // reject(error)
- // }
- // reader.readAsArrayBuffer(file)
- // })
- // console.log('111文件的md5哈希值是 fileContent:', fileContent)
- // 计算MD5哈希值
- let fileMd5 = await calculateFileMD5(file.raw)
- file.raw.md5 = fileMd5
- console.log('====开始获取File对象了...', file)
- let fileSuffix = '.' + file.raw.name.split('.').pop() // 得到.文件类型
- let currentFile = await new Promise((resolve, reject) => {
- console.log('====开始获取File对象了...')
- resolve(file.raw)
- reject('获取File对象失败')
- })
- // for (let i = 0; i < chunkCount.value; i++) {
- // // 文件开始遍历切片存入数组
- // const start = i * chunkSize.value
- // console.log('循环中的currentFile:', currentFile.value)
- // const end = Math.min(
- // start + chunkSize.value - 1,
- // currentFile.value.size - 1
- // )
- // chunkList.value[i] = currentFile.value.slice(start, end)
- // }
- let chunkList = splitFileByChunkSize(currentFile, chunkSize.value)
- console.log('file对象:', file)
- return {
- name: file.raw.name,
- size: currentFile.size,
- md5: fileMd5, // md5哈希值
- chunks: chunkList, // 分块列表
- fileSuffix: fileSuffix, // 后缀
- percents: 0,
- time: ''
- }
- // console.log('md5:', fileMd5.value)
- // console.log('chunkList:', chunkList.value)
- // console.log('fileSuffix:', fileSuffix.value)
- // console.log('currentFile:', currentFile.value)
- // uploadFileList.value.push({
- // name: file.raw.name,
- // size: currentFile.value.size,
- // md5: fileMd5.value, // md5哈希值
- // chunks: chunkList.value, // 分块列表
- // fileSuffix: fileSuffix.value, // 后缀
- // percents: 0,
- // time: ''
- // }) // 使用对象数组进行处理 ============
- // chunkList.value = []
- // console.log('uploadFileList是:', uploadFileList.value)
- // console.log('结束handleFileChange了')
- }
- const splitFileByChunkSize = (file, chunkSizeValue) => {
- const fileSize = file.size
- const chunkCount = Math.ceil(fileSize / chunkSizeValue) // 计算总分块数
- // console.log(
- // '统计:',
- // '块数',
- // chunkCount,
- // '文件大小',
- // fileSize,
- // ' 单块 ',
- // chunkSizeValue
- // )
- let chunkList = []
- for (let i = 0; i < chunkCount; i++) {
- const start = i * chunkSizeValue
- const min = start + chunkSizeValue
- console.log('奇怪:', ' start ', start, ' chunkSizeValue ', chunkSizeValue, ' min ', min)
- const end = Math.min(min, fileSize)
- // console.log(
- // '统计:',
- // ' start ',
- // start,
- // ' end ',
- // end,
- // ' 单块 ',
- // chunkSizeValue,
- // ' 比较谁大 ',
- // start + chunkSizeValue,
- // ' ssss ',
- // fileSize
- // )
- chunkList[i] = file.slice(start, end) // 注意:slice 是 [start, end) 前闭后开区间
- console.log(
- '准备开始:',
- ' 循环次数 ',
- i,
- ' 块数 ',
- chunkCount,
- '开始的大小',
- start,
- '结束的大小',
- end,
- ' file ',
- file.slice(start, end)
- )
- }
- console.log('分片完成:', chunkList)
- return chunkList
- }
- const checkMd5List = async (uploadFile) => {
- let md5List = []
- let element = {
- md5: uploadFile.md5,
- size: uploadFile.size,
- chunkSize: uploadFile.chunks.length,
- fileName: uploadFile.name,
- fileSuffix: uploadFile.fileSuffix
- }
- md5List.push(element)
- await axios
- .post(sysConfig.API_URL+'/api/webapp/minio/checkMd5List', md5List, { headers: { Token: tool.data.get('TOKEN') } })
- .then((res) => {
- console.log('文件上传返回结果:', res.data)
- // return
- var list = res.data
- if (list.length !== 0) {
- let upList = []
- for (let item of list) {
- console.log('item回来的', JSON.stringify(item))
- if (uploadFile.md5 === item.md5) {
- uploadFile.userFileId = item.userFileId
- //重要的步骤
- if (item.userFileId) {
- uploadFile.percents = 100
- pauseFlags.value[item.md5] = false
- // emit('onSuccess', uploadFile)
- }
- // upList.push(item)
- }
- }
- console.log('upList是:', upList)
- // uploadFileList.value.push(uploadFile)
- // emit('onSuccess', uploadFileList.value)
- } else {
- // clearFileList()
- }
- // 文件均存在minio中了,无需上传
- // if (uploadFileList.value.length === 0) {
- // successfulChunkPercents.value = 100
- // alert('文件上传成功')
- // }
- })
- .catch((error) => {
- console.log('检查返回错误', error)
- })
- }
- // 点击上传按钮触发多文件上传 ===============
- const uploadFilesList = async () => {
- if (upLoadTag.value == true) {
- message.loading('正在上传')
- return
- }
- upLoadTag.value = true
- emit('onUpLoading', upLoadTag.value)
- if (currentFile.value == null) {
- // alert('请选择文件后再上传!')
- message.error('请选择文件后再上传!')
- successfulChunkPercents.value = 0 // 重置百分比
- fileList.value = [] // 文件列表
- return
- }
- // 检查所有文件中是否存在未上传的,未上传则需要上传对应的文件 =========
- let md5List = []
- console.log('准备上传', uploadFileList.value)
- for (let i = 0; i < uploadFileList.value.length; i++) {
- let element = {
- // md5: uploadFileList.value[i].md5,
- md5: uploadFileList.value[i].md5,
- chunkSize: uploadFileList.value[i].chunks.length,
- fileName: uploadFileList.value[i].name,
- fileSuffix: uploadFileList.value[i].fileSuffix
- }
- md5List.push(element)
- }
- console.log('上传的md5_suffix_List是:', md5List)
- await axios
- .post(sysConfig.API_URL+'/api/webapp/minio/checkMd5List', md5List, { headers: { Token: tool.data.get('TOKEN') } })
- .then((res) => {
- console.log('文件上传返回结果:', res.data)
- // return
- var list = res.data
- if (list.length !== 0) {
- let upList = []
- for (let item1 of uploadFileList.value) {
- for (let item2 of list) {
- console.log('item回来的', JSON.stringify(item2))
- if (item1.md5 === item2.md5) {
- //重要的步骤
- item1.userFileId = item2.userFileId
- if (item1.userFileId) {
- item1.percents = 100
- }
- upList.push(item1)
- }
- }
- }
- console.log('upList是:', upList)
- uploadFileList.value = upList
- } else {
- clearFileList()
- }
- console.log('最后必须上传的文件:', uploadFileList.value)
- // 文件均存在minio中了,无需上传
- // if (uploadFileList.value.length === 0) {
- // successfulChunkPercents.value = 100
- // alert('文件上传成功')
- // }
- })
- .catch((error) => {
- console.log('检查返回错误', error)
- })
- // return
- console.log('开始上传', uploadFileList.value)
- // 检查上传的多个文件是否均存在,如果部分存在,进行剔除,剩余部分仍旧进行上传。
- // 分块的Promises化
- const chunkPromises = []
- // 上传分块的数组,校验是否完成上传
- const chunksUploadedList = []
- // 直接计算一共多少个分块
- uploadFileList.value.forEach((item) => {
- allChunks.value += item.chunks.length
- })
- console.log('所有文件加起来一共有多少个分块?', allChunks.value, uploadFileList.value)
- for (const item of uploadFileList.value) {
- const md5 = item.md5
- uploadChunks.value = 0
- if (item.userFileId == undefined || item.userFileId == null) {
- startTime.value = new Date().getTime() // 开始时间戳(毫秒
- totalSize.value = item.size // 文件总大小
- uploadedSize.value = 0
- for (let i = 0; i < item.chunks.length; i++) {
- console.log('上传第', i + 1, '个分片')
- let chunk = item.chunks[i]
- console.log('去上传...', i + 1, chunk)
- // 检查是否暂停
- console.log('看看...', ' 列表 ', pauseFlags.value, ' md5 ', md5)
- while (pauseFlags.value[md5] && true == pauseFlags.value[md5]) {
- await new Promise((resolve) => setTimeout(resolve, 100)) // 等待 1 秒后再次检查
- }
- chunkPromises.push(
- await uploadFilesChunk(
- {
- md5,
- chunk,
- chunkIndex: i + 1,
- fileSuffix: item.fileSuffix,
- chunkSize: item.chunks.length,
- fileName: item.name
- },
- () => {
- chunksUploaded.value++
- uploadChunks.value++
- // successfulChunkPercents.value = 100 * (uploadChunks.value / allChunks.value).toFixed(2)
- uploadedSize.value += chunk.size // 更新已上传大小
- const remainingTime = estimateRemainingTime()
- console.log(`预计剩余时间: ${formatTime(remainingTime)}`)
- item.percents = (100 * (uploadChunks.value / item.chunks.length)).toFixed(2)
- item.time = formatTime(remainingTime)
- console.log(
- '执行了自增...',
- '分片长度',
- item.chunks.length,
- '执行到多少了',
- uploadChunks.value,
- '百分比',
- 100 * (uploadChunks.value / item.chunks.length).toFixed(2)
- )
- console.log('this.uploadChunks:', uploadChunks.value)
- console.log('this.allChunks:', allChunks.value)
- console.log('进度:', (uploadChunks.value / allChunks.value).toFixed(2))
- }
- )
- )
- }
- }
- console.log('this.chunkUploaded是:', chunksUploaded.value)
- chunksUploadedList.push(chunksUploaded.value) // 存储不同文件的上传分块数量
- chunksUploaded.value = 0
- }
- await Promise.all(chunkPromises)
- console.log('上传完成!')
- console.log('chunksUploadList是:', chunksUploadedList)
- let mergeResults = []
- for (let i = 0; i < chunksUploadedList.length; i++) {
- console.log('this.uploadFileList' + i + '是:' + uploadFileList.value[i].chunks.length)
- console.log('chunksUploadedList' + i + '是:' + chunksUploadedList[i])
- if (uploadFileList.value[i].chunks.length === chunksUploadedList[i]) {
- const mergeResult = await axios.post(
- // `/api/webapp/disk/minio/merge?md5=${uploadFileList.value[i].md5}&fileSuffix=${uploadFileList.value[i].fileSuffix}&chunkTotal=${chunksUploadedList[i]}`
- sysConfig.API_URL+`/api/webapp/minio/merge?md5=${uploadFileList.value[i].md5}&fileSuffix=${uploadFileList.value[i].fileSuffix}&chunkTotal=${chunksUploadedList[i]}&fileName=${uploadFileList.value[i].name}&fileSize=${uploadFileList.value[i].size}`,
- null,
- { headers: { Token: tool.data.get('TOKEN') } }
- )
- // if (mergeResult.data.startsWith('[miss_chunk]')) {
- // alert('文件缺失,请重新上传')
- // return
- // }
- console.log('合并结果1:', mergeResult)
- uploadFileList.value[i].userFileId = mergeResult.data.userFileId
- // mergeResults.push(mergeResult)
- }
- }
- console.log('合并结果2:', uploadFileList.value)
- upLoadTag.value = false
- // 上传完成,清理任务状态
- delete uploadingTasks.value[md5]
- emit('onUpLoading', upLoadTag.value)
- let finalRes = true
- // emit('onSuccess', uploadFileList.value)
- // for (const result of mergeResults) {
- // if (result.data === '失败') {
- // finalRes = false
- // alert('上传失败!请重新上传')
- // return
- // } else {
- // alert('上传成功!')
- // successfulChunkPercents.value = 100
- // clearFileList()
- // // getList()
- // return
- // }
- // }
- }
- // 多文件上传分片 ============
- const uploadFilesChunk = async (data, onSuccess) => {
- console.log('进入了uploadFileChunk方法...')
- let retryTime = 5 //重试次数
- const formData = new FormData()
- formData.append('md5', data.md5)
- // formData.append('md5', md5)
- formData.append('chunkIndex', data.chunkIndex)
- formData.append('chunk', data.chunk)
- formData.append('chunkSize', data.chunkSize)
- formData.append('fileSuffix', data.fileSuffix)
- formData.append('fileName', data.fileName)
- return axios
- .post(sysConfig.API_URL+'/api/webapp/minio/upload', formData, {
- headers: { 'Content-Type': 'multipart/form-data', Token: tool.data.get('TOKEN') }
- })
- .then((res) => onSuccess())
- .catch((error) => {
- console.log('上传分片失败了...', error)
- if (retryTime > 0) {
- retryTime--
- return uploadChunk(data, onSuccess)
- }
- })
- }
- // 上传分片 旧
- const uploadChunk = (data, onSuccess) => {
- let retryTime = 5 //重试次数
- const formData = new FormData()
- // formData.append('identifier', fileMd5.value)
- formData.append('md5', data.md5)
- // formData.append('md5', md5)
- formData.append('chunkIndex', data.chunkIndex)
- formData.append('chunk', data.chunk)
- formData.append('chunkSize', data.chunkSize)
- formData.append('fileSuffix', data.fileSuffix)
- formData.append('fileName', data.fileName)
- return axios
- .post(sysConfig.API_URL+'/api/webapp/minio/upload', formData, {
- headers: { 'Content-Type': 'multipart/form-data', Token: tool.data.get('TOKEN') }
- })
- .then((res) => onSuccess())
- .catch((error) => {
- if (retryTime > 0) {
- retryTime--
- return uploadChunk(data, onSuccess)
- }
- })
- }
- // 删除文件
- const deleteFile = (url) => {
- axios
- .get(sysConfig.API_URL+`/api/webapp/disk/delete?url=` + url)
- .then((res) => {
- console.log('删除文件:', res.data)
- alert(res.data ? '删除成功!' : '删除失败!')
- // getList()
- })
- .catch((error) => {
- console.log('删除失败:', error)
- })
- console.log('url是:', url)
- }
- const downloadFile = (url) => {
- window.location.href = url
- }
- const beforeUpload = async (file) => {
- console.log('选择了文件', file)
- if(uploadFileList.value.length >= props.uploadCount){
- message.error('超过上传条目' + props.uploadCount + "条")
- return false
- }
- let upFile = await handleFileChange({ raw: file })
- console.log('可以上传的文件内容是', upFile)
- // 检查本地 uploadFileList 是否已存在该 md5 文件
- const exists = uploadFileList.value.some((item) => item.md5 === upFile.md5)
- if (exists) {
- message.warning('该文件已存在,不再重复添加')
- return false
- }
- await checkMd5List(upFile)
- uploadFileList.value.push(upFile)
- emit('onSuccess', uploadFileList.value)
- const activeTasks = Object.keys(uploadingTasks.value).filter((key) => uploadingTasks.value[key])
- if (activeTasks.length < 2) {
- pauseFlags.value[upFile.md5] = false
- uploadingTasks.value[upFile.md5] = true
- } else {
- pauseFlags.value[upFile.md5] = true
- message.warning('上传队列已满,将进入暂停状态')
- }
- await uploadSingleFile(upFile)
- return false // 阻止默认上传
- }
- const handleChange = (info) => {
- const { file } = info
- if (file.status === 'removed') {
- fileList.value = []
- clearFileList()
- }
- }
- const uploadSingleFile = async (fileObj) => {
- const file = fileObj
- const md5 = file.md5
- const index = uploadFileList.value.findIndex((item) => item.md5 === md5)
- if (index === -1) return
- const item = uploadFileList.value[index]
- if (!item || item.userFileId) return
- // // 如果是暂停状态则不执行上传
- // while (pauseFlags.value[md5]) {
- // await new Promise((resolve) => setTimeout(resolve, 500))
- // }
- // 添加到正在上传任务中
- uploadingTasks.value[md5] = true
- file.startTime = new Date().getTime()
- file.uploadedSize = 0
- const chunkPromises = []
- for (let i = 0; i < item.chunks.length; i++) {
- let chunk = item.chunks[i]
- while (pauseFlags.value[md5]) {
- await new Promise((resolve) => setTimeout(resolve, 500))
- }
- chunkPromises.push(
- await uploadFilesChunk(
- {
- md5,
- chunk,
- chunkIndex: i + 1,
- fileSuffix: item.fileSuffix,
- chunkSize: item.chunks.length,
- fileName: item.name
- },
- () => {
- // chunksUploaded.value++
- // uploadChunks.value++
- // successfulChunkPercents.value = 100 * (uploadChunks.value / allChunks.value).toFixed(2)
- item.uploadedSize += chunk.size // 更新已上传大小
- const remainingTime = estimateRemainingTime(item.startTime, item.uploadedSize, item.size)
- console.log(`预计剩余时间: ${formatTime(remainingTime)}`)
- // item.percents = (100 * (uploadChunks.value / item.chunks.length)).toFixed(2)
- item.time = formatTime(remainingTime)
- const percent = ((i + 1) / item.chunks.length) * 100
- item.percents = percent.toFixed(2)
- console.log(`我得名字: `, item.name, ' i ', i, ' item.chunks.length ', item.chunks.length)
- // item.time = formatTime(estimateRemainingTime())
- }
- )
- )
- }
- await Promise.all(chunkPromises)
- // 合并分片
- const mergeResult = await axios.post(
- sysConfig.API_URL+`/api/webapp/minio/merge?md5=${md5}&fileSuffix=${item.fileSuffix}&chunkTotal=${item.chunks.length}&fileName=${item.name}&fileSize=${item.size}`,
- null,
- { headers: { Token: tool.data.get('TOKEN') } }
- )
- uploadFileList.value[index].userFileId = mergeResult.data.userFileId
- uploadFileList.value[index].percents = 100
- uploadingTasks.value[item.md5] = false
- // item.time = '上传完成'
- // 尝试恢复一个被暂停的任务
- autoResumePausedUpload()
- // upLoadTag.value = false
- emit('onSuccess', uploadFileList.value)
- }
- // watch(
- // () => uploadFileList.value,
- // (newValue) => {
- // emit('onSuccess', newValue)
- // },
- // { immediate: true }
- // )
- const autoResumePausedUpload = async () => {
- const activeTasks = Object.keys(uploadingTasks.value).filter((key) => uploadingTasks.value[key])
- if (activeTasks.length >= 2) return
- // 查找第一个被暂停的文件
- for (let i = 0; i < uploadFileList.value.length; i++) {
- const item = uploadFileList.value[i]
- if (item.percents > 0 && item.percents < 100 && pauseFlags.value[item.md5] === true) {
- console.log(`自动恢复 ${item.name}`)
- pauseFlags.value[item.md5] = false
- uploadingTasks.value[item.md5] = true
- await uploadSingleFile(item)
- break
- }
- }
- }
- const customRequest = () => {}
- const getList = () => {
- axios
- .get('http://127.0.0.1:9000/api/webapp/disk/minio/list')
- .then((res) => {
- this.uploadList = res.data
- console.log('获取列表结果成功:', res.data)
- })
- .catch((error) => {
- console.error('获取列表失败:', error)
- })
- }
- const clearFileList = () => {
- successfulChunkPercents.value = 0
- uploadFileList.value = []
- fileList.value = []
- }
- const open = () => {
- clearFileList()
- }
- onMounted(() => {
- // getList()
- })
- defineExpose({open})
- </script>
- <style scoped></style>
|