miniyun.js 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374
  1. import {defineStore} from 'pinia'
  2. import {ref, onMounted} from 'vue'
  3. import axios from 'axios'
  4. import SparkMD5 from 'spark-md5'
  5. import tool from '@/utils/tool'
  6. import {message} from 'ant-design-vue'
  7. import sysConfig from '@/config/index'
  8. import resourceAuditApi from '@/api/resourceAudit.js'
  9. import EventBus from "@/utils/EventBus";
  10. export const miniyunStore = defineStore({
  11. id: 'miniyun',
  12. state: () => ({
  13. pauseFlags: {}, // 控制每个文件是否暂停 { md5: true/false }
  14. uploadingTasks: {}, // 正在上传的任务 { md5: true }
  15. checkingFiles: new Set(), // 正在检查的文件MD5
  16. checkedFiles: new Map(), // 已检查的文件结果缓存
  17. //当前选中的文件
  18. currentFile: null,
  19. spinning: false,
  20. chunkSize: 5 * 1024 * 1024,
  21. uploadedSize: 0, // 已上传文件大小(字节)
  22. chunkCount: 0,
  23. chunksUploaded: 0,
  24. fileMd5: '', //
  25. // const emit = defineEmits(['onUpLoading', 'onSuccess'])
  26. progress: {
  27. strokeColor: {
  28. '0%': '#108ee9',
  29. '100%': '#87d068'
  30. },
  31. strokeWidth: 3,
  32. format: (percent) => `${parseFloat(percent.toFixed(2))}%`,
  33. class: 'test'
  34. },
  35. allChunks: 0, // 文件的md5值
  36. successfulChunkPercents: 0, // 上传成功的分片百分比
  37. fileSuffix: '', // 文件后缀
  38. chunkList: [], // 文件后缀
  39. uploadList: [], // 文件后缀
  40. fileList: [],// 文件后缀
  41. uploadFileList: [], // 文件后缀
  42. uploadChunks: [],// 文件后缀
  43. uploadFileListTemp: [],
  44. upLoadTag: false, // 文件的md5值
  45. startTime: 0, // 开始时间戳(毫秒
  46. totalSize: 0, // 开始时间戳(毫秒
  47. tempIndex: 0,
  48. //文件数据放一起
  49. fileForms: [],
  50. }),
  51. getters: {
  52. getFileForms: (state) => state.fileForms,
  53. getPauseFlags: (state) => state.pauseFlags,
  54. },
  55. actions: {
  56. async addFileForms(fileForm) {
  57. this.fileForms.push(fileForm)
  58. for (let i = 0; i < fileForm.uploadFileList.length; i++) {
  59. await this.checkMd5List(fileForm.uploadFileList[i])
  60. await this.uploadSingleFile(fileForm.uploadFileList[i])
  61. }
  62. //准备开启去下载
  63. // for (let i = 0; i < fileForm.uploadFileList.length; i++) {
  64. // this.tempIndex+=1
  65. // fileForm.uploadFileList[i].tempIndex = this.tempIndex
  66. // this.uploadFileListTemp.push(fileForm.uploadFileList[i])
  67. // }
  68. },
  69. handlerRemoveItem(mmyIndex, mmmyIndex) {
  70. // let myIndex = -1
  71. // for (let i = 0; i < this.uploadFileListTemp.length; i++) {
  72. // if(this.uploadFileListTemp[i].tempIndex == item.tempIndex){
  73. // myIndex = i
  74. // }
  75. // }
  76. // if(myIndex != -1){
  77. // this.uploadFileListTemp.splice(myIndex, 1)
  78. // }
  79. // let mmyIndex = -1
  80. // let mmmyIndex = -1
  81. // for (let i = 0; i < this.fileForms.length; i++) {
  82. // for (let ii = 0; ii < this.fileForms[i].uploadFileList.length; ii++) {
  83. // if(this.fileForms[i].uploadFileList[ii].tempIndex == item.tempIndex){
  84. // mmyIndex = i
  85. // mmmyIndex = ii
  86. // }
  87. // }
  88. // }
  89. // if(mmyIndex != -1 && mmmyIndex != -1){
  90. // this.fileForms[mmyIndex].uploadFileList.splice(mmmyIndex, 1)
  91. // }
  92. this.fileForms[mmyIndex].uploadFileList.splice(mmmyIndex, 1)
  93. },
  94. pauseUpload(md5) {
  95. this.pauseFlags[md5] = true
  96. },
  97. resumeUpload(md5) {
  98. this.pauseFlags[md5] = false
  99. },
  100. async checkMd5List(uploadFile) {
  101. // 标记文件正在检查
  102. this.checkingFiles.add(uploadFile.md5)
  103. const md5List = [{
  104. md5: uploadFile.md5,
  105. size: uploadFile.size,
  106. chunkSize: uploadFile.chunks.length,
  107. fileName: uploadFile.name,
  108. fileSuffix: uploadFile.fileSuffix,
  109. affiliationFuncType : 0
  110. }]
  111. await axios
  112. .post(sysConfig.API_URL + '/api/webapp/minio/checkMd5List', md5List, {headers: {Token: tool.data.get('TOKEN')}})
  113. .then((res) => {
  114. console.log('文件上传返回结果:', res.data)
  115. // return
  116. var list = res.data
  117. if (list.length !== 0) {
  118. let upList = []
  119. for (let item of list) {
  120. console.log('item回来的', JSON.stringify(item))
  121. if (uploadFile.md5 === item.md5) {
  122. uploadFile.userFileId = item.userFileId
  123. //重要的步骤
  124. if (item.userFileId) {
  125. uploadFile.percents = 100
  126. this.checkedFiles.set(uploadFile.md5, {
  127. userFileId: item.userFileId,
  128. status: 'uploaded'
  129. })
  130. // emit('onSuccess', uploadFile)
  131. }
  132. // upList.push(item)
  133. }
  134. }
  135. console.log('upList是:', upList)
  136. // uploadFileList.value.push(uploadFile)
  137. // emit('onSuccess', uploadFileList.value)
  138. }
  139. // 从正在检查列表中移除
  140. this.checkingFiles.delete(uploadFile.md5)
  141. return uploadFile
  142. // 文件均存在minio中了,无需上传
  143. // if (uploadFileList.value.length === 0) {
  144. // successfulChunkPercents.value = 100
  145. // alert('文件上传成功')
  146. // }
  147. })
  148. .catch((error) => {
  149. console.log('检查返回错误', error)
  150. // 从正在检查列表中移除
  151. this.checkingFiles.delete(uploadFile.md5)
  152. throw error
  153. })
  154. },
  155. async uploadFilesChunk(data, onSuccess) {
  156. console.log('进入了uploadFileChunk方法...')
  157. let retryTime = 5 //重试次数
  158. const formData = new FormData()
  159. formData.append('md5', data.md5)
  160. // formData.append('md5', md5)
  161. formData.append('chunkIndex', data.chunkIndex)
  162. formData.append('chunk', data.chunk)
  163. formData.append('chunkSize', data.chunkSize)
  164. formData.append('fileSuffix', data.fileSuffix)
  165. formData.append('fileName', data.fileName)
  166. formData.append('affiliationFuncType', data.affiliationFuncType)
  167. return axios
  168. .post(sysConfig.API_URL + '/api/webapp/minio/upload', formData, {
  169. headers: {'Content-Type': 'multipart/form-data', Token: tool.data.get('TOKEN')}
  170. })
  171. .then((res) => onSuccess())
  172. .catch((error) => {
  173. console.log('上传分片失败了...', error)
  174. if (retryTime > 0) {
  175. retryTime--
  176. return this.uploadChunk(data, onSuccess)
  177. }
  178. })
  179. },
  180. // 上传分片 旧
  181. async uploadChunk(data, onSuccess) {
  182. let retryTime = 5 //重试次数
  183. const formData = new FormData()
  184. // formData.append('identifier', fileMd5.value)
  185. formData.append('md5', data.md5)
  186. // formData.append('md5', md5)
  187. formData.append('chunkIndex', data.chunkIndex)
  188. formData.append('chunk', data.chunk)
  189. formData.append('chunkSize', data.chunkSize)
  190. formData.append('fileSuffix', data.fileSuffix)
  191. formData.append('fileName', data.fileName)
  192. formData.append('affiliationFuncType', data.affiliationFuncType)
  193. return axios
  194. .post(sysConfig.API_URL + '/api/webapp/minio/upload', formData, {
  195. headers: {'Content-Type': 'multipart/form-data', Token: tool.data.get('TOKEN')}
  196. })
  197. .then((res) => onSuccess())
  198. .catch((error) => {
  199. if (retryTime > 0) {
  200. retryTime--
  201. return this.uploadChunk(data, onSuccess)
  202. }
  203. })
  204. },
  205. calculateSpeed(startTime, uploadedSize) {
  206. const currentTime = new Date().getTime()
  207. const timeElapsed = (currentTime - startTime) / 1000 // 单位:秒
  208. if (timeElapsed > 0) {
  209. const speed = uploadedSize / timeElapsed // 单位:字节/秒
  210. return speed
  211. }
  212. return 0
  213. },
  214. estimateRemainingTime(startTime, uploadedSize, totalSize) {
  215. console.log('疑问', ' 总的 ', totalSize, ' 变化的 ', uploadedSize)
  216. const remainingSize = totalSize - uploadedSize // 剩余文件大小
  217. const speed = this.calculateSpeed(startTime, uploadedSize) // 平均上传速度(字节/秒)
  218. if (speed > 0) {
  219. const remainingTimeSeconds = remainingSize / speed // 剩余时间(秒)
  220. return remainingTimeSeconds
  221. }
  222. return Infinity // 如果上传速度为 0,则无法估算
  223. },
  224. formatTime(seconds) {
  225. const minutes = Math.floor(seconds / 60)
  226. const secs = Math.floor(seconds % 60)
  227. if (minutes == 0 && secs == 0) {
  228. return ''
  229. }
  230. return `${minutes} 分 ${secs} 秒`
  231. },
  232. async uploadSingleFile(fileObj) {
  233. const file = fileObj
  234. const md5 = file.md5
  235. // const index = uploadFileList.value.findIndex((item) => item.md5 === md5)
  236. //
  237. // if (index === -1) return
  238. const item = fileObj
  239. if (item && item.userFileId) {
  240. this.getUp(fileObj)
  241. return
  242. }
  243. // // 如果是暂停状态则不执行上传
  244. // while (pauseFlags.value[md5]) {
  245. // await new Promise((resolve) => setTimeout(resolve, 500))
  246. // }
  247. // 添加到正在上传任务中
  248. // uploadingTasks.value[md5] = true
  249. file.startTime = new Date().getTime()
  250. file.uploadedSize = 0
  251. const chunkPromises = []
  252. for (let i = 0; i < item.chunks.length; i++) {
  253. let chunk = item.chunks[i]
  254. while (this.pauseFlags[md5]) {
  255. await new Promise((resolve) => setTimeout(resolve, 500))
  256. }
  257. chunkPromises.push(
  258. await this.uploadFilesChunk(
  259. {
  260. affiliationFuncType : 0,
  261. md5,
  262. chunk,
  263. chunkIndex: i + 1,
  264. fileSuffix: item.fileSuffix,
  265. chunkSize: item.chunks.length,
  266. fileName: item.name
  267. },
  268. () => {
  269. // chunksUploaded.value++
  270. // uploadChunks.value++
  271. // successfulChunkPercents.value = 100 * (uploadChunks.value / allChunks.value).toFixed(2)
  272. item.uploadedSize += chunk.size // 更新已上传大小
  273. const remainingTime = this.estimateRemainingTime(item.startTime, item.uploadedSize, item.size)
  274. console.log(`预计剩余时间: ${this.formatTime(remainingTime)}`)
  275. // item.percents = (100 * (uploadChunks.value / item.chunks.length)).toFixed(2)
  276. item.time = this.formatTime(remainingTime)
  277. const percent = ((i + 1) / item.chunks.length) * 100
  278. item.percents = percent.toFixed(2)
  279. console.log(`我得名字: `, item.name, ' i ', i, ' item.chunks.length ', item.chunks.length)
  280. // item.time = formatTime(estimateRemainingTime())
  281. }
  282. )
  283. )
  284. }
  285. await Promise.all(chunkPromises)
  286. item.affiliationFuncType = 0
  287. // 合并分片
  288. const mergeResult = await axios.post(
  289. sysConfig.API_URL + `/api/webapp/minio/merge?md5=${md5}&fileSuffix=${item.fileSuffix}&chunkTotal=${item.chunks.length}&fileName=${item.name}&fileSize=${item.size}&affiliationFuncType=${item.affiliationFuncType}`,
  290. null,
  291. {headers: {Token: tool.data.get('TOKEN')}}
  292. )
  293. console.log('怎么说呢', ' 啊网络请求 ', mergeResult)
  294. fileObj.userFileId = mergeResult.data.userFileId
  295. fileObj.percents = 100
  296. // uploadingTasks.value[item.md5] = false
  297. // item.time = '上传完成'
  298. // 尝试恢复一个被暂停的任务
  299. // autoResumePausedUpload()
  300. // upLoadTag.value = false
  301. // emit('onSuccess', uploadFileList.value)
  302. this.getUp(fileObj)
  303. },
  304. async getUp(fileObj) {
  305. for (let i = 0; i < this.fileForms.length; i++) {
  306. console.log('怎么说呢', this.fileForms[i].upTag != undefined,' 里面的 ', this.fileForms[i], ' 外面的1 ', fileObj)
  307. if (this.fileForms[i].upTag == undefined) {
  308. let count = 0
  309. let list = []
  310. for (let ii = 0; ii < this.fileForms[i].uploadFileList.length; ii++) {
  311. console.log('怎么说呢', ' 里面的 ', this.fileForms[i], ' 外面的2 ', fileObj)
  312. let item = this.fileForms[i].uploadFileList[ii]
  313. if (item.userFileId != undefined && item.percents == 100){
  314. count ++
  315. list.push(item.userFileId)
  316. }
  317. }
  318. if(this.fileForms[i].uploadFileList.length == count){
  319. let formData = this.fileForms[i]
  320. formData.userfileIds = list.join(',')
  321. //去上传
  322. let res = await resourceAuditApi.stuLinkResourceRecordAdd(formData)
  323. // .then((res) => {
  324. // Modal.success({ content: '资源上传成功' })
  325. // })
  326. // .catch((err) => {
  327. // Modal.success({ content: '资源上传失败' })
  328. // console.log(err)
  329. // })
  330. console.log('上传至hi偶',res)
  331. this.fileForms[i].upTag = true
  332. EventBus.emit('onUpTag')
  333. }
  334. }
  335. }
  336. }
  337. },
  338. })