index.vue 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807
  1. <template>
  2. <div>
  3. <a-upload-dragger
  4. :file-list="fileList"
  5. :before-upload="beforeUpload"
  6. @change="handleChange"
  7. :show-upload-list="false"
  8. :customRequest="customRequest"
  9. :multiple="false"
  10. :drag="true"
  11. :progress="progress"
  12. >
  13. <div style="padding: 40px; text-align: center">
  14. <span class="text"> 点击上传或将文件拖拽至此区域上传 </span>
  15. <p class="text">按住Ctrl可同时多选,支持上传PPT/excel/pdf/mp4/zip/rar,等单个文件不能超过2G</p>
  16. </div>
  17. </a-upload-dragger>
  18. <!-- <div style="margin-bottom: 20px">
  19. <a-button v-if="uploadFileList.length > 0" type="primary" @click="uploadFilesList">上传</a-button>
  20. </div> -->
  21. <div v-for="(item, index) in uploadFileList" :key="index">
  22. <div style="padding: 10px">
  23. <div style="display: flex; width: 100%; align-items: center; justify-content: space-between">
  24. <div>
  25. <span>{{ item.name.length > 20 ? item.name.slice(0, 20) + '...' + item.fileSuffix : item.name }}</span>
  26. </div>
  27. <div>
  28. <span v-if="item.time != ''" style="display: block; color: blue">{{ item.time }}</span>
  29. </div>
  30. <div>
  31. <div>
  32. <span
  33. v-if="item.percents == 0 || item.percents == 100"
  34. style="color: red; cursor: pointer; margin-left: 10px"
  35. @click="handlerRemoveItem(index)"
  36. >删除</span
  37. >
  38. <span
  39. v-if="
  40. item.percents >= 0 &&
  41. item.percents < 100 &&
  42. (pauseFlags[item.md5] == false || pauseFlags[item.md5] == undefined)
  43. "
  44. style="color: blue; cursor: pointer; margin-left: 10px"
  45. @click="pauseUpload(index)"
  46. >暂停</span
  47. >
  48. <span
  49. v-if="item.percents >= 0 && item.percents < 100 && pauseFlags[item.md5] == true"
  50. style="color: green; cursor: pointer; margin-left: 10px"
  51. @click="resumeUpload(index)"
  52. >恢复</span
  53. >
  54. </div>
  55. </div>
  56. </div>
  57. <a-progress :percent="item.percents" />
  58. </div>
  59. </div>
  60. <!-- <div> -->
  61. <!-- <el-progress :text-inside="true" :stroke-width="20" :percentage="successfulChunkPercents" status="success" /> -->
  62. <!-- <a-progress :percent="successfulChunkPercents" /> -->
  63. <!-- </div> -->
  64. <!-- 已上传列表-->
  65. <!-- <el-table :data="uploadList" border style="width: 100%">
  66. <el-table-column fixed prop="id.date" label="日期" width="150"> </el-table-column>
  67. <el-table-column prop="url" label="下载地址"> </el-table-column>
  68. <el-table-column label="操作">
  69. <template #default="scope">
  70. <el-button link type="primary" size="small" @click.prevent="deleteFile(scope.row.url)"> 删除 </el-button>
  71. <el-button link type="primary" size="small" @click.prevent="downloadFile(scope.row.url)"> 下载 </el-button>
  72. </template>
  73. </el-table-column>
  74. </el-table> -->
  75. </div>
  76. </template>
  77. <script setup>
  78. import { ref, onMounted } from 'vue'
  79. import axios from 'axios'
  80. import SparkMD5 from 'spark-md5'
  81. import tool from '@/utils/tool'
  82. import { message } from 'ant-design-vue'
  83. import sysConfig from '@/config/index'
  84. const pauseFlags = ref({}) // 控制每个文件是否暂停 { md5: true/false }
  85. const uploadingTasks = ref({}) // 正在上传的任务 { md5: true }
  86. //当前选中的文件
  87. const currentFile = ref(null)
  88. const chunkSize = ref(5 * 1024 * 1024)
  89. const uploadedSize = ref(0) // 已上传文件大小(字节)
  90. const chunkCount = ref(0)
  91. const chunksUploaded = ref(0)
  92. const fileMd5 = ref('') //
  93. const emit = defineEmits(['onUpLoading', 'onSuccess'])
  94. const progress = {
  95. strokeColor: {
  96. '0%': '#108ee9',
  97. '100%': '#87d068'
  98. },
  99. strokeWidth: 3,
  100. format: (percent) => `${parseFloat(percent.toFixed(2))}%`,
  101. class: 'test'
  102. }
  103. const allChunks = ref(0) // 文件的md5值
  104. const successfulChunkPercents = ref(0) // 上传成功的分片百分比
  105. const fileSuffix = ref('') // 文件后缀
  106. const chunkList = ref([]) // 文件后缀
  107. const uploadList = ref([]) // 文件后缀
  108. const fileList = ref([]) // 文件后缀
  109. const uploadFileList = ref([]) // 文件后缀
  110. const uploadChunks = ref([]) // 文件后缀
  111. const upLoadTag = ref(false) // 文件的md5值
  112. const startTime = ref(0) // 开始时间戳(毫秒
  113. const totalSize = ref(0) // 开始时间戳(毫秒
  114. const props = defineProps({
  115. uploadCount: {
  116. type: Number,
  117. default: () => 10
  118. }
  119. })
  120. const handlerRemoveItem = (index) => {
  121. const item = uploadFileList.value[index]
  122. if (item && item.md5) {
  123. delete pauseFlags.value[item.md5] // 清理暂停标志
  124. }
  125. uploadFileList.value.splice(index, 1)
  126. emit('onSuccess', uploadFileList.value)
  127. }
  128. const pauseUpload = (index) => {
  129. const item = uploadFileList.value[index]
  130. if (item && item.md5) {
  131. pauseFlags.value[item.md5] = true
  132. uploadingTasks.value[item.md5] = false
  133. }
  134. }
  135. const resumeUpload = (index) => {
  136. const item = uploadFileList.value[index]
  137. if (!item || !item.md5) return
  138. pauseFlags.value[item.md5] = false
  139. // 如果当前上传任务小于 2,则开始上传
  140. const activeTasks = Object.keys(uploadingTasks.value).filter((key) => uploadingTasks.value[key])
  141. if (activeTasks.length < 2) {
  142. uploadingTasks.value[item.md5] = true
  143. // uploadSingleFile(item)
  144. } else {
  145. pauseFlags.value[item.md5] = true
  146. }
  147. }
  148. const calculateFileMD5 = (file) => {
  149. return new Promise((resolve, reject) => {
  150. const reader = new FileReader()
  151. const spark = new SparkMD5.ArrayBuffer()
  152. reader.onload = (e) => {
  153. spark.append(e.target.result)
  154. const md5 = spark.end()
  155. resolve(md5)
  156. }
  157. reader.onerror = () => reject(new Error('文件读取失败'))
  158. reader.readAsArrayBuffer(file)
  159. })
  160. }
  161. const updateProgress = (chunkSize) => {
  162. uploadedSize.value += chunkSize
  163. const percent = Math.round((uploadedSize.value / totalSize.value) * 100)
  164. console.log(`上传进度: ${percent}%`)
  165. }
  166. const calculateSpeed = (startTime, uploadedSize) => {
  167. const currentTime = new Date().getTime()
  168. const timeElapsed = (currentTime - startTime) / 1000 // 单位:秒
  169. if (timeElapsed > 0) {
  170. const speed = uploadedSize / timeElapsed // 单位:字节/秒
  171. return speed
  172. }
  173. return 0
  174. }
  175. const estimateRemainingTime = (startTime, uploadedSize, totalSize) => {
  176. console.log('疑问', ' 总的 ', totalSize, ' 变化的 ', uploadedSize)
  177. const remainingSize = totalSize - uploadedSize // 剩余文件大小
  178. const speed = calculateSpeed(startTime, uploadedSize) // 平均上传速度(字节/秒)
  179. if (speed > 0) {
  180. const remainingTimeSeconds = remainingSize / speed // 剩余时间(秒)
  181. return remainingTimeSeconds
  182. }
  183. return Infinity // 如果上传速度为 0,则无法估算
  184. }
  185. const formatTime = (seconds) => {
  186. const minutes = Math.floor(seconds / 60)
  187. const secs = Math.floor(seconds % 60)
  188. if (minutes == 0 && secs == 0) {
  189. return ''
  190. }
  191. return `${minutes} 分 ${secs} 秒`
  192. }
  193. // 异步方法:选择文件时触发 ============
  194. const handleFileChange = async (file) => {
  195. // const reader = new FileReader()
  196. // const spark = new SparkMD5.ArrayBuffer()
  197. // console.log("读取文件",file.raw)
  198. // reader.readAsArrayBuffer(file.raw) // 异步读取文件内容
  199. // const fileContent = await new Promise((resolve, reject) => {
  200. // reader.onload = (event) => {
  201. // console.log('开始读取文件了...', event, reader.result)
  202. // spark.append(event.target.result)
  203. // resolve(spark.end())
  204. // }
  205. // reader.onerror = (error) => {
  206. // console.log('读取文件时发生错误...', error)
  207. // reject(error)
  208. // }
  209. // reader.readAsArrayBuffer(file)
  210. // })
  211. // console.log('111文件的md5哈希值是 fileContent:', fileContent)
  212. // 计算MD5哈希值
  213. let fileMd5 = await calculateFileMD5(file.raw)
  214. file.raw.md5 = fileMd5
  215. console.log('====开始获取File对象了...', file)
  216. let fileSuffix = '.' + file.raw.name.split('.').pop() // 得到.文件类型
  217. let currentFile = await new Promise((resolve, reject) => {
  218. console.log('====开始获取File对象了...')
  219. resolve(file.raw)
  220. reject('获取File对象失败')
  221. })
  222. // for (let i = 0; i < chunkCount.value; i++) {
  223. // // 文件开始遍历切片存入数组
  224. // const start = i * chunkSize.value
  225. // console.log('循环中的currentFile:', currentFile.value)
  226. // const end = Math.min(
  227. // start + chunkSize.value - 1,
  228. // currentFile.value.size - 1
  229. // )
  230. // chunkList.value[i] = currentFile.value.slice(start, end)
  231. // }
  232. let chunkList = splitFileByChunkSize(currentFile, chunkSize.value)
  233. console.log('file对象:', file)
  234. return {
  235. name: file.raw.name,
  236. size: currentFile.size,
  237. md5: fileMd5, // md5哈希值
  238. chunks: chunkList, // 分块列表
  239. fileSuffix: fileSuffix, // 后缀
  240. percents: 0,
  241. time: ''
  242. }
  243. // console.log('md5:', fileMd5.value)
  244. // console.log('chunkList:', chunkList.value)
  245. // console.log('fileSuffix:', fileSuffix.value)
  246. // console.log('currentFile:', currentFile.value)
  247. // uploadFileList.value.push({
  248. // name: file.raw.name,
  249. // size: currentFile.value.size,
  250. // md5: fileMd5.value, // md5哈希值
  251. // chunks: chunkList.value, // 分块列表
  252. // fileSuffix: fileSuffix.value, // 后缀
  253. // percents: 0,
  254. // time: ''
  255. // }) // 使用对象数组进行处理 ============
  256. // chunkList.value = []
  257. // console.log('uploadFileList是:', uploadFileList.value)
  258. // console.log('结束handleFileChange了')
  259. }
  260. const splitFileByChunkSize = (file, chunkSizeValue) => {
  261. const fileSize = file.size
  262. const chunkCount = Math.ceil(fileSize / chunkSizeValue) // 计算总分块数
  263. // console.log(
  264. // '统计:',
  265. // '块数',
  266. // chunkCount,
  267. // '文件大小',
  268. // fileSize,
  269. // ' 单块 ',
  270. // chunkSizeValue
  271. // )
  272. let chunkList = []
  273. for (let i = 0; i < chunkCount; i++) {
  274. const start = i * chunkSizeValue
  275. const min = start + chunkSizeValue
  276. console.log('奇怪:', ' start ', start, ' chunkSizeValue ', chunkSizeValue, ' min ', min)
  277. const end = Math.min(min, fileSize)
  278. // console.log(
  279. // '统计:',
  280. // ' start ',
  281. // start,
  282. // ' end ',
  283. // end,
  284. // ' 单块 ',
  285. // chunkSizeValue,
  286. // ' 比较谁大 ',
  287. // start + chunkSizeValue,
  288. // ' ssss ',
  289. // fileSize
  290. // )
  291. chunkList[i] = file.slice(start, end) // 注意:slice 是 [start, end) 前闭后开区间
  292. console.log(
  293. '准备开始:',
  294. ' 循环次数 ',
  295. i,
  296. ' 块数 ',
  297. chunkCount,
  298. '开始的大小',
  299. start,
  300. '结束的大小',
  301. end,
  302. ' file ',
  303. file.slice(start, end)
  304. )
  305. }
  306. console.log('分片完成:', chunkList)
  307. return chunkList
  308. }
  309. const checkMd5List = async (uploadFile) => {
  310. let md5List = []
  311. let element = {
  312. md5: uploadFile.md5,
  313. chunkSize: uploadFile.chunks.length,
  314. fileName: uploadFile.name,
  315. fileSuffix: uploadFile.fileSuffix
  316. }
  317. md5List.push(element)
  318. await axios
  319. .post(sysConfig.API_URL+'/api/webapp/minio/checkMd5List', md5List, { headers: { Token: tool.data.get('TOKEN') } })
  320. .then((res) => {
  321. console.log('文件上传返回结果:', res.data)
  322. // return
  323. var list = res.data
  324. if (list.length !== 0) {
  325. let upList = []
  326. for (let item of list) {
  327. console.log('item回来的', JSON.stringify(item))
  328. if (uploadFile.md5 === item.md5) {
  329. uploadFile.userFileId = item.userFileId
  330. //重要的步骤
  331. if (item.userFileId) {
  332. uploadFile.percents = 100
  333. pauseFlags.value[item.md5] = false
  334. // emit('onSuccess', uploadFile)
  335. }
  336. // upList.push(item)
  337. }
  338. }
  339. console.log('upList是:', upList)
  340. // uploadFileList.value.push(uploadFile)
  341. // emit('onSuccess', uploadFileList.value)
  342. } else {
  343. // clearFileList()
  344. }
  345. // 文件均存在minio中了,无需上传
  346. // if (uploadFileList.value.length === 0) {
  347. // successfulChunkPercents.value = 100
  348. // alert('文件上传成功')
  349. // }
  350. })
  351. .catch((error) => {
  352. console.log('检查返回错误', error)
  353. })
  354. }
  355. // 点击上传按钮触发多文件上传 ===============
  356. const uploadFilesList = async () => {
  357. if (upLoadTag.value == true) {
  358. message.loading('正在上传')
  359. return
  360. }
  361. upLoadTag.value = true
  362. emit('onUpLoading', upLoadTag.value)
  363. if (currentFile.value == null) {
  364. // alert('请选择文件后再上传!')
  365. message.error('请选择文件后再上传!')
  366. successfulChunkPercents.value = 0 // 重置百分比
  367. fileList.value = [] // 文件列表
  368. return
  369. }
  370. // 检查所有文件中是否存在未上传的,未上传则需要上传对应的文件 =========
  371. let md5List = []
  372. console.log('准备上传', uploadFileList.value)
  373. for (let i = 0; i < uploadFileList.value.length; i++) {
  374. let element = {
  375. // md5: uploadFileList.value[i].md5,
  376. md5: uploadFileList.value[i].md5,
  377. chunkSize: uploadFileList.value[i].chunks.length,
  378. fileName: uploadFileList.value[i].name,
  379. fileSuffix: uploadFileList.value[i].fileSuffix
  380. }
  381. md5List.push(element)
  382. }
  383. console.log('上传的md5_suffix_List是:', md5List)
  384. await axios
  385. .post(sysConfig.API_URL+'/api/webapp/minio/checkMd5List', md5List, { headers: { Token: tool.data.get('TOKEN') } })
  386. .then((res) => {
  387. console.log('文件上传返回结果:', res.data)
  388. // return
  389. var list = res.data
  390. if (list.length !== 0) {
  391. let upList = []
  392. for (let item1 of uploadFileList.value) {
  393. for (let item2 of list) {
  394. console.log('item回来的', JSON.stringify(item2))
  395. if (item1.md5 === item2.md5) {
  396. //重要的步骤
  397. item1.userFileId = item2.userFileId
  398. if (item1.userFileId) {
  399. item1.percents = 100
  400. }
  401. upList.push(item1)
  402. }
  403. }
  404. }
  405. console.log('upList是:', upList)
  406. uploadFileList.value = upList
  407. } else {
  408. clearFileList()
  409. }
  410. console.log('最后必须上传的文件:', uploadFileList.value)
  411. // 文件均存在minio中了,无需上传
  412. // if (uploadFileList.value.length === 0) {
  413. // successfulChunkPercents.value = 100
  414. // alert('文件上传成功')
  415. // }
  416. })
  417. .catch((error) => {
  418. console.log('检查返回错误', error)
  419. })
  420. // return
  421. console.log('开始上传', uploadFileList.value)
  422. // 检查上传的多个文件是否均存在,如果部分存在,进行剔除,剩余部分仍旧进行上传。
  423. // 分块的Promises化
  424. const chunkPromises = []
  425. // 上传分块的数组,校验是否完成上传
  426. const chunksUploadedList = []
  427. // 直接计算一共多少个分块
  428. uploadFileList.value.forEach((item) => {
  429. allChunks.value += item.chunks.length
  430. })
  431. console.log('所有文件加起来一共有多少个分块?', allChunks.value, uploadFileList.value)
  432. for (const item of uploadFileList.value) {
  433. const md5 = item.md5
  434. uploadChunks.value = 0
  435. if (item.userFileId == undefined || item.userFileId == null) {
  436. startTime.value = new Date().getTime() // 开始时间戳(毫秒
  437. totalSize.value = item.size // 文件总大小
  438. uploadedSize.value = 0
  439. for (let i = 0; i < item.chunks.length; i++) {
  440. console.log('上传第', i + 1, '个分片')
  441. let chunk = item.chunks[i]
  442. console.log('去上传...', i + 1, chunk)
  443. // 检查是否暂停
  444. console.log('看看...', ' 列表 ', pauseFlags.value, ' md5 ', md5)
  445. while (pauseFlags.value[md5] && true == pauseFlags.value[md5]) {
  446. await new Promise((resolve) => setTimeout(resolve, 100)) // 等待 1 秒后再次检查
  447. }
  448. chunkPromises.push(
  449. await uploadFilesChunk(
  450. {
  451. md5,
  452. chunk,
  453. chunkIndex: i + 1,
  454. fileSuffix: item.fileSuffix,
  455. chunkSize: item.chunks.length,
  456. fileName: item.name
  457. },
  458. () => {
  459. chunksUploaded.value++
  460. uploadChunks.value++
  461. // successfulChunkPercents.value = 100 * (uploadChunks.value / allChunks.value).toFixed(2)
  462. uploadedSize.value += chunk.size // 更新已上传大小
  463. const remainingTime = estimateRemainingTime()
  464. console.log(`预计剩余时间: ${formatTime(remainingTime)}`)
  465. item.percents = (100 * (uploadChunks.value / item.chunks.length)).toFixed(2)
  466. item.time = formatTime(remainingTime)
  467. console.log(
  468. '执行了自增...',
  469. '分片长度',
  470. item.chunks.length,
  471. '执行到多少了',
  472. uploadChunks.value,
  473. '百分比',
  474. 100 * (uploadChunks.value / item.chunks.length).toFixed(2)
  475. )
  476. console.log('this.uploadChunks:', uploadChunks.value)
  477. console.log('this.allChunks:', allChunks.value)
  478. console.log('进度:', (uploadChunks.value / allChunks.value).toFixed(2))
  479. }
  480. )
  481. )
  482. }
  483. }
  484. console.log('this.chunkUploaded是:', chunksUploaded.value)
  485. chunksUploadedList.push(chunksUploaded.value) // 存储不同文件的上传分块数量
  486. chunksUploaded.value = 0
  487. }
  488. await Promise.all(chunkPromises)
  489. console.log('上传完成!')
  490. console.log('chunksUploadList是:', chunksUploadedList)
  491. let mergeResults = []
  492. for (let i = 0; i < chunksUploadedList.length; i++) {
  493. console.log('this.uploadFileList' + i + '是:' + uploadFileList.value[i].chunks.length)
  494. console.log('chunksUploadedList' + i + '是:' + chunksUploadedList[i])
  495. if (uploadFileList.value[i].chunks.length === chunksUploadedList[i]) {
  496. const mergeResult = await axios.post(
  497. // `/api/webapp/disk/minio/merge?md5=${uploadFileList.value[i].md5}&fileSuffix=${uploadFileList.value[i].fileSuffix}&chunkTotal=${chunksUploadedList[i]}`
  498. 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}`,
  499. null,
  500. { headers: { Token: tool.data.get('TOKEN') } }
  501. )
  502. // if (mergeResult.data.startsWith('[miss_chunk]')) {
  503. // alert('文件缺失,请重新上传')
  504. // return
  505. // }
  506. console.log('合并结果1:', mergeResult)
  507. uploadFileList.value[i].userFileId = mergeResult.data.userFileId
  508. // mergeResults.push(mergeResult)
  509. }
  510. }
  511. console.log('合并结果2:', uploadFileList.value)
  512. upLoadTag.value = false
  513. // 上传完成,清理任务状态
  514. delete uploadingTasks.value[md5]
  515. emit('onUpLoading', upLoadTag.value)
  516. let finalRes = true
  517. // emit('onSuccess', uploadFileList.value)
  518. // for (const result of mergeResults) {
  519. // if (result.data === '失败') {
  520. // finalRes = false
  521. // alert('上传失败!请重新上传')
  522. // return
  523. // } else {
  524. // alert('上传成功!')
  525. // successfulChunkPercents.value = 100
  526. // clearFileList()
  527. // // getList()
  528. // return
  529. // }
  530. // }
  531. }
  532. // 多文件上传分片 ============
  533. const uploadFilesChunk = async (data, onSuccess) => {
  534. console.log('进入了uploadFileChunk方法...')
  535. let retryTime = 5 //重试次数
  536. const formData = new FormData()
  537. formData.append('md5', data.md5)
  538. // formData.append('md5', md5)
  539. formData.append('chunkIndex', data.chunkIndex)
  540. formData.append('chunk', data.chunk)
  541. formData.append('chunkSize', data.chunkSize)
  542. formData.append('fileSuffix', data.fileSuffix)
  543. formData.append('fileName', data.fileName)
  544. return axios
  545. .post(sysConfig.API_URL+'/api/webapp/minio/upload', formData, {
  546. headers: { 'Content-Type': 'multipart/form-data', Token: tool.data.get('TOKEN') }
  547. })
  548. .then((res) => onSuccess())
  549. .catch((error) => {
  550. console.log('上传分片失败了...', error)
  551. if (retryTime > 0) {
  552. retryTime--
  553. return uploadChunk(data, onSuccess)
  554. }
  555. })
  556. }
  557. // 上传分片 旧
  558. const uploadChunk = (data, onSuccess) => {
  559. let retryTime = 5 //重试次数
  560. const formData = new FormData()
  561. // formData.append('identifier', fileMd5.value)
  562. formData.append('md5', data.md5)
  563. // formData.append('md5', md5)
  564. formData.append('chunkIndex', data.chunkIndex)
  565. formData.append('chunk', data.chunk)
  566. formData.append('chunkSize', data.chunkSize)
  567. formData.append('fileSuffix', data.fileSuffix)
  568. formData.append('fileName', data.fileName)
  569. return axios
  570. .post(sysConfig.API_URL+'/api/webapp/minio/upload', formData, {
  571. headers: { 'Content-Type': 'multipart/form-data', Token: tool.data.get('TOKEN') }
  572. })
  573. .then((res) => onSuccess())
  574. .catch((error) => {
  575. if (retryTime > 0) {
  576. retryTime--
  577. return uploadChunk(data, onSuccess)
  578. }
  579. })
  580. }
  581. // 删除文件
  582. const deleteFile = (url) => {
  583. axios
  584. .get(sysConfig.API_URL+`/api/webapp/disk/delete?url=` + url)
  585. .then((res) => {
  586. console.log('删除文件:', res.data)
  587. alert(res.data ? '删除成功!' : '删除失败!')
  588. // getList()
  589. })
  590. .catch((error) => {
  591. console.log('删除失败:', error)
  592. })
  593. console.log('url是:', url)
  594. }
  595. const downloadFile = (url) => {
  596. window.location.href = url
  597. }
  598. const beforeUpload = async (file) => {
  599. console.log('选择了文件', file)
  600. if(uploadFileList.value.length >= props.uploadCount){
  601. message.error('超过上传条目' + props.uploadCount + "条")
  602. return false
  603. }
  604. let upFile = await handleFileChange({ raw: file })
  605. console.log('可以上传的文件内容是', upFile)
  606. // 检查本地 uploadFileList 是否已存在该 md5 文件
  607. const exists = uploadFileList.value.some((item) => item.md5 === upFile.md5)
  608. if (exists) {
  609. message.warning('该文件已存在,不再重复添加')
  610. return false
  611. }
  612. await checkMd5List(upFile)
  613. uploadFileList.value.push(upFile)
  614. emit('onSuccess', uploadFileList.value)
  615. const activeTasks = Object.keys(uploadingTasks.value).filter((key) => uploadingTasks.value[key])
  616. if (activeTasks.length < 2) {
  617. pauseFlags.value[upFile.md5] = false
  618. uploadingTasks.value[upFile.md5] = true
  619. } else {
  620. pauseFlags.value[upFile.md5] = true
  621. message.warning('上传队列已满,将进入暂停状态')
  622. }
  623. await uploadSingleFile(upFile)
  624. return false // 阻止默认上传
  625. }
  626. const handleChange = (info) => {
  627. const { file } = info
  628. if (file.status === 'removed') {
  629. fileList.value = []
  630. clearFileList()
  631. }
  632. }
  633. const uploadSingleFile = async (fileObj) => {
  634. const file = fileObj
  635. const md5 = file.md5
  636. const index = uploadFileList.value.findIndex((item) => item.md5 === md5)
  637. if (index === -1) return
  638. const item = uploadFileList.value[index]
  639. if (!item || item.userFileId) return
  640. // // 如果是暂停状态则不执行上传
  641. // while (pauseFlags.value[md5]) {
  642. // await new Promise((resolve) => setTimeout(resolve, 500))
  643. // }
  644. // 添加到正在上传任务中
  645. uploadingTasks.value[md5] = true
  646. file.startTime = new Date().getTime()
  647. file.uploadedSize = 0
  648. const chunkPromises = []
  649. for (let i = 0; i < item.chunks.length; i++) {
  650. let chunk = item.chunks[i]
  651. while (pauseFlags.value[md5]) {
  652. await new Promise((resolve) => setTimeout(resolve, 500))
  653. }
  654. chunkPromises.push(
  655. await uploadFilesChunk(
  656. {
  657. md5,
  658. chunk,
  659. chunkIndex: i + 1,
  660. fileSuffix: item.fileSuffix,
  661. chunkSize: item.chunks.length,
  662. fileName: item.name
  663. },
  664. () => {
  665. // chunksUploaded.value++
  666. // uploadChunks.value++
  667. // successfulChunkPercents.value = 100 * (uploadChunks.value / allChunks.value).toFixed(2)
  668. item.uploadedSize += chunk.size // 更新已上传大小
  669. const remainingTime = estimateRemainingTime(item.startTime, item.uploadedSize, item.size)
  670. console.log(`预计剩余时间: ${formatTime(remainingTime)}`)
  671. // item.percents = (100 * (uploadChunks.value / item.chunks.length)).toFixed(2)
  672. item.time = formatTime(remainingTime)
  673. const percent = ((i + 1) / item.chunks.length) * 100
  674. item.percents = percent.toFixed(2)
  675. console.log(`我得名字: `, item.name, ' i ', i, ' item.chunks.length ', item.chunks.length)
  676. // item.time = formatTime(estimateRemainingTime())
  677. }
  678. )
  679. )
  680. }
  681. await Promise.all(chunkPromises)
  682. // 合并分片
  683. const mergeResult = await axios.post(
  684. sysConfig.API_URL+`/api/webapp/minio/merge?md5=${md5}&fileSuffix=${item.fileSuffix}&chunkTotal=${item.chunks.length}&fileName=${item.name}&fileSize=${item.size}`,
  685. null,
  686. { headers: { Token: tool.data.get('TOKEN') } }
  687. )
  688. uploadFileList.value[index].userFileId = mergeResult.data.userFileId
  689. uploadFileList.value[index].percents = 100
  690. uploadingTasks.value[item.md5] = false
  691. // item.time = '上传完成'
  692. // 尝试恢复一个被暂停的任务
  693. autoResumePausedUpload()
  694. // upLoadTag.value = false
  695. emit('onSuccess', uploadFileList.value)
  696. }
  697. // watch(
  698. // () => uploadFileList.value,
  699. // (newValue) => {
  700. // emit('onSuccess', newValue)
  701. // },
  702. // { immediate: true }
  703. // )
  704. const autoResumePausedUpload = async () => {
  705. const activeTasks = Object.keys(uploadingTasks.value).filter((key) => uploadingTasks.value[key])
  706. if (activeTasks.length >= 2) return
  707. // 查找第一个被暂停的文件
  708. for (let i = 0; i < uploadFileList.value.length; i++) {
  709. const item = uploadFileList.value[i]
  710. if (item.percents > 0 && item.percents < 100 && pauseFlags.value[item.md5] === true) {
  711. console.log(`自动恢复 ${item.name}`)
  712. pauseFlags.value[item.md5] = false
  713. uploadingTasks.value[item.md5] = true
  714. await uploadSingleFile(item)
  715. break
  716. }
  717. }
  718. }
  719. const customRequest = () => {}
  720. const getList = () => {
  721. axios
  722. .get('http://127.0.0.1:9000/api/webapp/disk/minio/list')
  723. .then((res) => {
  724. this.uploadList = res.data
  725. console.log('获取列表结果成功:', res.data)
  726. })
  727. .catch((error) => {
  728. console.error('获取列表失败:', error)
  729. })
  730. }
  731. const clearFileList = () => {
  732. successfulChunkPercents.value = 0
  733. uploadFileList.value = []
  734. fileList.value = []
  735. }
  736. const open = () => {
  737. clearFileList()
  738. }
  739. onMounted(() => {
  740. // getList()
  741. })
  742. defineExpose({open})
  743. </script>
  744. <style scoped></style>