index.vue 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809
  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. size: uploadFile.size,
  314. chunkSize: uploadFile.chunks.length,
  315. fileName: uploadFile.name,
  316. fileSuffix: uploadFile.fileSuffix
  317. }
  318. md5List.push(element)
  319. await axios
  320. .post(sysConfig.API_URL+'/api/webapp/minio/checkMd5List', md5List, { headers: { Token: tool.data.get('TOKEN') } })
  321. .then((res) => {
  322. console.log('文件上传返回结果:', res.data)
  323. // return
  324. var list = res.data
  325. if (list.length !== 0) {
  326. let upList = []
  327. for (let item of list) {
  328. console.log('item回来的', JSON.stringify(item))
  329. if (uploadFile.md5 === item.md5) {
  330. uploadFile.userFileId = item.userFileId
  331. //重要的步骤
  332. if (item.userFileId) {
  333. uploadFile.percents = 100
  334. pauseFlags.value[item.md5] = false
  335. // emit('onSuccess', uploadFile)
  336. }
  337. // upList.push(item)
  338. }
  339. }
  340. console.log('upList是:', upList)
  341. // uploadFileList.value.push(uploadFile)
  342. // emit('onSuccess', uploadFileList.value)
  343. } else {
  344. // clearFileList()
  345. }
  346. // 文件均存在minio中了,无需上传
  347. // if (uploadFileList.value.length === 0) {
  348. // successfulChunkPercents.value = 100
  349. // alert('文件上传成功')
  350. // }
  351. })
  352. .catch((error) => {
  353. console.log('检查返回错误', error)
  354. })
  355. }
  356. // 点击上传按钮触发多文件上传 ===============
  357. const uploadFilesList = async () => {
  358. if (upLoadTag.value == true) {
  359. message.loading('正在上传')
  360. return
  361. }
  362. upLoadTag.value = true
  363. emit('onUpLoading', upLoadTag.value)
  364. if (currentFile.value == null) {
  365. // alert('请选择文件后再上传!')
  366. message.error('请选择文件后再上传!')
  367. successfulChunkPercents.value = 0 // 重置百分比
  368. fileList.value = [] // 文件列表
  369. return
  370. }
  371. // 检查所有文件中是否存在未上传的,未上传则需要上传对应的文件 =========
  372. let md5List = []
  373. console.log('准备上传', uploadFileList.value)
  374. for (let i = 0; i < uploadFileList.value.length; i++) {
  375. let element = {
  376. // md5: uploadFileList.value[i].md5,
  377. md5: uploadFileList.value[i].md5,
  378. chunkSize: uploadFileList.value[i].chunks.length,
  379. fileName: uploadFileList.value[i].name,
  380. fileSuffix: uploadFileList.value[i].fileSuffix
  381. }
  382. md5List.push(element)
  383. }
  384. console.log('上传的md5_suffix_List是:', md5List)
  385. await axios
  386. .post(sysConfig.API_URL+'/api/webapp/minio/checkMd5List', md5List, { headers: { Token: tool.data.get('TOKEN') } })
  387. .then((res) => {
  388. console.log('文件上传返回结果:', res.data)
  389. // return
  390. var list = res.data
  391. if (list.length !== 0) {
  392. let upList = []
  393. for (let item1 of uploadFileList.value) {
  394. for (let item2 of list) {
  395. console.log('item回来的', JSON.stringify(item2))
  396. if (item1.md5 === item2.md5) {
  397. //重要的步骤
  398. item1.userFileId = item2.userFileId
  399. if (item1.userFileId) {
  400. item1.percents = 100
  401. }
  402. upList.push(item1)
  403. }
  404. }
  405. }
  406. console.log('upList是:', upList)
  407. uploadFileList.value = upList
  408. } else {
  409. clearFileList()
  410. }
  411. console.log('最后必须上传的文件:', uploadFileList.value)
  412. // 文件均存在minio中了,无需上传
  413. // if (uploadFileList.value.length === 0) {
  414. // successfulChunkPercents.value = 100
  415. // alert('文件上传成功')
  416. // }
  417. })
  418. .catch((error) => {
  419. console.log('检查返回错误', error)
  420. })
  421. // return
  422. console.log('开始上传', uploadFileList.value)
  423. // 检查上传的多个文件是否均存在,如果部分存在,进行剔除,剩余部分仍旧进行上传。
  424. // 分块的Promises化
  425. const chunkPromises = []
  426. // 上传分块的数组,校验是否完成上传
  427. const chunksUploadedList = []
  428. // 直接计算一共多少个分块
  429. uploadFileList.value.forEach((item) => {
  430. allChunks.value += item.chunks.length
  431. })
  432. console.log('所有文件加起来一共有多少个分块?', allChunks.value, uploadFileList.value)
  433. for (const item of uploadFileList.value) {
  434. const md5 = item.md5
  435. uploadChunks.value = 0
  436. if (item.userFileId == undefined || item.userFileId == null) {
  437. startTime.value = new Date().getTime() // 开始时间戳(毫秒
  438. totalSize.value = item.size // 文件总大小
  439. uploadedSize.value = 0
  440. for (let i = 0; i < item.chunks.length; i++) {
  441. console.log('上传第', i + 1, '个分片')
  442. let chunk = item.chunks[i]
  443. console.log('去上传...', i + 1, chunk)
  444. // 检查是否暂停
  445. console.log('看看...', ' 列表 ', pauseFlags.value, ' md5 ', md5)
  446. while (pauseFlags.value[md5] && true == pauseFlags.value[md5]) {
  447. await new Promise((resolve) => setTimeout(resolve, 100)) // 等待 1 秒后再次检查
  448. }
  449. chunkPromises.push(
  450. await uploadFilesChunk(
  451. {
  452. md5,
  453. chunk,
  454. chunkIndex: i + 1,
  455. fileSuffix: item.fileSuffix,
  456. chunkSize: item.chunks.length,
  457. fileName: item.name
  458. },
  459. () => {
  460. chunksUploaded.value++
  461. uploadChunks.value++
  462. // successfulChunkPercents.value = 100 * (uploadChunks.value / allChunks.value).toFixed(2)
  463. uploadedSize.value += chunk.size // 更新已上传大小
  464. const remainingTime = estimateRemainingTime()
  465. console.log(`预计剩余时间: ${formatTime(remainingTime)}`)
  466. item.percents = (100 * (uploadChunks.value / item.chunks.length)).toFixed(2)
  467. item.time = formatTime(remainingTime)
  468. console.log(
  469. '执行了自增...',
  470. '分片长度',
  471. item.chunks.length,
  472. '执行到多少了',
  473. uploadChunks.value,
  474. '百分比',
  475. 100 * (uploadChunks.value / item.chunks.length).toFixed(2)
  476. )
  477. console.log('this.uploadChunks:', uploadChunks.value)
  478. console.log('this.allChunks:', allChunks.value)
  479. console.log('进度:', (uploadChunks.value / allChunks.value).toFixed(2))
  480. }
  481. )
  482. )
  483. }
  484. }
  485. console.log('this.chunkUploaded是:', chunksUploaded.value)
  486. chunksUploadedList.push(chunksUploaded.value) // 存储不同文件的上传分块数量
  487. chunksUploaded.value = 0
  488. }
  489. await Promise.all(chunkPromises)
  490. console.log('上传完成!')
  491. console.log('chunksUploadList是:', chunksUploadedList)
  492. let mergeResults = []
  493. for (let i = 0; i < chunksUploadedList.length; i++) {
  494. console.log('this.uploadFileList' + i + '是:' + uploadFileList.value[i].chunks.length)
  495. console.log('chunksUploadedList' + i + '是:' + chunksUploadedList[i])
  496. if (uploadFileList.value[i].chunks.length === chunksUploadedList[i]) {
  497. const mergeResult = await axios.post(
  498. // `/api/webapp/disk/minio/merge?md5=${uploadFileList.value[i].md5}&fileSuffix=${uploadFileList.value[i].fileSuffix}&chunkTotal=${chunksUploadedList[i]}`
  499. 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}`,
  500. null,
  501. { headers: { Token: tool.data.get('TOKEN') } }
  502. )
  503. // if (mergeResult.data.startsWith('[miss_chunk]')) {
  504. // alert('文件缺失,请重新上传')
  505. // return
  506. // }
  507. console.log('合并结果1:', mergeResult)
  508. uploadFileList.value[i].userFileId = mergeResult.data.userFileId
  509. // mergeResults.push(mergeResult)
  510. }
  511. }
  512. console.log('合并结果2:', uploadFileList.value)
  513. upLoadTag.value = false
  514. // 上传完成,清理任务状态
  515. delete uploadingTasks.value[md5]
  516. emit('onUpLoading', upLoadTag.value)
  517. let finalRes = true
  518. // emit('onSuccess', uploadFileList.value)
  519. // for (const result of mergeResults) {
  520. // if (result.data === '失败') {
  521. // finalRes = false
  522. // alert('上传失败!请重新上传')
  523. // return
  524. // } else {
  525. // alert('上传成功!')
  526. // successfulChunkPercents.value = 100
  527. // clearFileList()
  528. // // getList()
  529. // return
  530. // }
  531. // }
  532. }
  533. // 多文件上传分片 ============
  534. const uploadFilesChunk = async (data, onSuccess) => {
  535. console.log('进入了uploadFileChunk方法...')
  536. let retryTime = 5 //重试次数
  537. const formData = new FormData()
  538. formData.append('md5', data.md5)
  539. // formData.append('md5', md5)
  540. formData.append('chunkIndex', data.chunkIndex)
  541. formData.append('chunk', data.chunk)
  542. formData.append('chunkSize', data.chunkSize)
  543. formData.append('fileSuffix', data.fileSuffix)
  544. formData.append('fileName', data.fileName)
  545. return axios
  546. .post(sysConfig.API_URL+'/api/webapp/minio/upload', formData, {
  547. headers: { 'Content-Type': 'multipart/form-data', Token: tool.data.get('TOKEN') }
  548. })
  549. .then((res) => onSuccess())
  550. .catch((error) => {
  551. console.log('上传分片失败了...', error)
  552. if (retryTime > 0) {
  553. retryTime--
  554. return uploadChunk(data, onSuccess)
  555. }
  556. })
  557. }
  558. // 上传分片 旧
  559. const uploadChunk = (data, onSuccess) => {
  560. let retryTime = 5 //重试次数
  561. const formData = new FormData()
  562. // formData.append('identifier', fileMd5.value)
  563. formData.append('md5', data.md5)
  564. // formData.append('md5', md5)
  565. formData.append('chunkIndex', data.chunkIndex)
  566. formData.append('chunk', data.chunk)
  567. formData.append('chunkSize', data.chunkSize)
  568. formData.append('fileSuffix', data.fileSuffix)
  569. formData.append('fileName', data.fileName)
  570. return axios
  571. .post(sysConfig.API_URL+'/api/webapp/minio/upload', formData, {
  572. headers: { 'Content-Type': 'multipart/form-data', Token: tool.data.get('TOKEN') }
  573. })
  574. .then((res) => onSuccess())
  575. .catch((error) => {
  576. if (retryTime > 0) {
  577. retryTime--
  578. return uploadChunk(data, onSuccess)
  579. }
  580. })
  581. }
  582. // 删除文件
  583. const deleteFile = (url) => {
  584. axios
  585. .get(sysConfig.API_URL+`/api/webapp/disk/delete?url=` + url)
  586. .then((res) => {
  587. console.log('删除文件:', res.data)
  588. alert(res.data ? '删除成功!' : '删除失败!')
  589. // getList()
  590. })
  591. .catch((error) => {
  592. console.log('删除失败:', error)
  593. })
  594. console.log('url是:', url)
  595. }
  596. const downloadFile = (url) => {
  597. window.location.href = url
  598. }
  599. const beforeUpload = async (file) => {
  600. console.log('选择了文件', file)
  601. if(uploadFileList.value.length >= props.uploadCount){
  602. message.error('超过上传条目' + props.uploadCount + "条")
  603. return false
  604. }
  605. let upFile = await handleFileChange({ raw: file })
  606. console.log('可以上传的文件内容是', upFile)
  607. // 检查本地 uploadFileList 是否已存在该 md5 文件
  608. const exists = uploadFileList.value.some((item) => item.md5 === upFile.md5)
  609. if (exists) {
  610. message.warning('该文件已存在,不再重复添加')
  611. return false
  612. }
  613. await checkMd5List(upFile)
  614. uploadFileList.value.push(upFile)
  615. emit('onSuccess', uploadFileList.value)
  616. const activeTasks = Object.keys(uploadingTasks.value).filter((key) => uploadingTasks.value[key])
  617. if (activeTasks.length < 2) {
  618. pauseFlags.value[upFile.md5] = false
  619. uploadingTasks.value[upFile.md5] = true
  620. } else {
  621. pauseFlags.value[upFile.md5] = true
  622. message.warning('上传队列已满,将进入暂停状态')
  623. }
  624. await uploadSingleFile(upFile)
  625. return false // 阻止默认上传
  626. }
  627. const handleChange = (info) => {
  628. const { file } = info
  629. if (file.status === 'removed') {
  630. fileList.value = []
  631. clearFileList()
  632. }
  633. }
  634. const uploadSingleFile = async (fileObj) => {
  635. const file = fileObj
  636. const md5 = file.md5
  637. const index = uploadFileList.value.findIndex((item) => item.md5 === md5)
  638. if (index === -1) return
  639. const item = uploadFileList.value[index]
  640. if (!item || item.userFileId) return
  641. // // 如果是暂停状态则不执行上传
  642. // while (pauseFlags.value[md5]) {
  643. // await new Promise((resolve) => setTimeout(resolve, 500))
  644. // }
  645. // 添加到正在上传任务中
  646. uploadingTasks.value[md5] = true
  647. file.startTime = new Date().getTime()
  648. file.uploadedSize = 0
  649. const chunkPromises = []
  650. for (let i = 0; i < item.chunks.length; i++) {
  651. let chunk = item.chunks[i]
  652. while (pauseFlags.value[md5]) {
  653. await new Promise((resolve) => setTimeout(resolve, 500))
  654. }
  655. chunkPromises.push(
  656. await uploadFilesChunk(
  657. {
  658. md5,
  659. chunk,
  660. chunkIndex: i + 1,
  661. fileSuffix: item.fileSuffix,
  662. chunkSize: item.chunks.length,
  663. fileName: item.name
  664. },
  665. () => {
  666. // chunksUploaded.value++
  667. // uploadChunks.value++
  668. // successfulChunkPercents.value = 100 * (uploadChunks.value / allChunks.value).toFixed(2)
  669. item.uploadedSize += chunk.size // 更新已上传大小
  670. const remainingTime = estimateRemainingTime(item.startTime, item.uploadedSize, item.size)
  671. console.log(`预计剩余时间: ${formatTime(remainingTime)}`)
  672. // item.percents = (100 * (uploadChunks.value / item.chunks.length)).toFixed(2)
  673. item.time = formatTime(remainingTime)
  674. const percent = ((i + 1) / item.chunks.length) * 100
  675. item.percents = percent.toFixed(2)
  676. console.log(`我得名字: `, item.name, ' i ', i, ' item.chunks.length ', item.chunks.length)
  677. // item.time = formatTime(estimateRemainingTime())
  678. }
  679. )
  680. )
  681. }
  682. await Promise.all(chunkPromises)
  683. // 合并分片
  684. const mergeResult = await axios.post(
  685. sysConfig.API_URL+`/api/webapp/minio/merge?md5=${md5}&fileSuffix=${item.fileSuffix}&chunkTotal=${item.chunks.length}&fileName=${item.name}&fileSize=${item.size}`,
  686. null,
  687. { headers: { Token: tool.data.get('TOKEN') } }
  688. )
  689. uploadFileList.value[index].userFileId = mergeResult.data.userFileId
  690. uploadFileList.value[index].percents = 100
  691. uploadingTasks.value[item.md5] = false
  692. // item.time = '上传完成'
  693. // 尝试恢复一个被暂停的任务
  694. autoResumePausedUpload()
  695. // upLoadTag.value = false
  696. emit('onSuccess', uploadFileList.value)
  697. }
  698. // watch(
  699. // () => uploadFileList.value,
  700. // (newValue) => {
  701. // emit('onSuccess', newValue)
  702. // },
  703. // { immediate: true }
  704. // )
  705. const autoResumePausedUpload = async () => {
  706. const activeTasks = Object.keys(uploadingTasks.value).filter((key) => uploadingTasks.value[key])
  707. if (activeTasks.length >= 2) return
  708. // 查找第一个被暂停的文件
  709. for (let i = 0; i < uploadFileList.value.length; i++) {
  710. const item = uploadFileList.value[i]
  711. if (item.percents > 0 && item.percents < 100 && pauseFlags.value[item.md5] === true) {
  712. console.log(`自动恢复 ${item.name}`)
  713. pauseFlags.value[item.md5] = false
  714. uploadingTasks.value[item.md5] = true
  715. await uploadSingleFile(item)
  716. break
  717. }
  718. }
  719. }
  720. const customRequest = () => {}
  721. const getList = () => {
  722. axios
  723. .get('http://127.0.0.1:9000/api/webapp/disk/minio/list')
  724. .then((res) => {
  725. this.uploadList = res.data
  726. console.log('获取列表结果成功:', res.data)
  727. })
  728. .catch((error) => {
  729. console.error('获取列表失败:', error)
  730. })
  731. }
  732. const clearFileList = () => {
  733. successfulChunkPercents.value = 0
  734. uploadFileList.value = []
  735. fileList.value = []
  736. }
  737. const open = () => {
  738. clearFileList()
  739. }
  740. onMounted(() => {
  741. // getList()
  742. })
  743. defineExpose({open})
  744. </script>
  745. <style scoped></style>