|
|
@@ -1,4 +1,7 @@
|
|
|
+
|
|
|
+import { ElMessage } from 'element-plus';
|
|
|
import axiosInstance from "@/apis/axios.config";
|
|
|
+import SparkMD5 from 'spark-md5'
|
|
|
|
|
|
const FILE_PREFIX = "/api/file"
|
|
|
|
|
|
@@ -13,6 +16,86 @@ const fileApis = {
|
|
|
timeout:300000 // 添加超时时间等待
|
|
|
});
|
|
|
},
|
|
|
+ async uploadChunkFile(file, userId, assignmentId, duration) {
|
|
|
+ const chunkCount = Math.ceil(file.size / chunk_size)
|
|
|
+ // 创建文件hash
|
|
|
+ const md5 = await createFileMd5(file)
|
|
|
+ // 创建文件分片
|
|
|
+ const chunkList = createChunkFileList(file)
|
|
|
+ // 创建分片对象
|
|
|
+ const chunkListObj = createChunksFileObj(chunkList, file, md5, chunkCount)
|
|
|
+ const promises = uploadChunkFile(chunkListObj, userId, assignmentId, duration)
|
|
|
+ await Promise.all(promises)
|
|
|
+ }
|
|
|
+
|
|
|
+
|
|
|
+}
|
|
|
+
|
|
|
+
|
|
|
+const createFileMd5 = (file) =>{
|
|
|
+ const reader = new FileReader()
|
|
|
+ return new Promise((resolve, reject) => {
|
|
|
+ reader.onload = (e) =>{
|
|
|
+ const md5 = SparkMD5.ArrayBuffer.hash(e.target.result)
|
|
|
+ resolve(md5)
|
|
|
+ }
|
|
|
+ reader.onerror = (error) => {
|
|
|
+ reject(error)
|
|
|
+ }
|
|
|
+ reader.readAsArrayBuffer(file)
|
|
|
+ })
|
|
|
+
|
|
|
+}
|
|
|
+const chunk_size = 5 * 1024 * 1024
|
|
|
+ // 创建文件分片
|
|
|
+ const createChunkFileList = (file) => {
|
|
|
+ let current = 0
|
|
|
+ const chunkList = []
|
|
|
+ while(current < file.size){
|
|
|
+ chunkList.push(file.slice(current, Math.min(current + chunk_size, file.size)))
|
|
|
+ current += chunk_size
|
|
|
+ }
|
|
|
+ return chunkList
|
|
|
}
|
|
|
|
|
|
+const createChunksFileObj = (chunkList, file, md5, chunkCount) => {
|
|
|
+ return chunkList.map(((chunk, index) => {
|
|
|
+ return {
|
|
|
+ file: chunk,
|
|
|
+ hash: md5,
|
|
|
+ name: file.name,
|
|
|
+ index:index,
|
|
|
+ chunkCount
|
|
|
+ }
|
|
|
+ }))
|
|
|
+
|
|
|
+}
|
|
|
+
|
|
|
+const uploadChunkFile = (chunkListObj, userId, assignmentId, duration) => {
|
|
|
+
|
|
|
+ return chunkListObj.map(async(chunk) =>{
|
|
|
+ try{
|
|
|
+ const formData = new FormData();
|
|
|
+ formData.append("file", chunk.file)
|
|
|
+ formData.append("fileName", chunk.name)
|
|
|
+ formData.append('fileMd5', chunk.hash)
|
|
|
+ formData.append('chunkCount', chunk.chunkCount)
|
|
|
+ formData.append('currentIndex', chunk.index)
|
|
|
+ formData.append('userId', userId)
|
|
|
+ formData.append('assignmentId', assignmentId)
|
|
|
+ formData.append('duration', duration)
|
|
|
+ return axiosInstance.post(`${FILE_PREFIX}/large`, formData, {
|
|
|
+ headers: {
|
|
|
+ 'Content-Type': 'multipart/form-data'
|
|
|
+ }
|
|
|
+ });
|
|
|
+
|
|
|
+ } catch (error) {
|
|
|
+ return Promise.reject(error)
|
|
|
+ }
|
|
|
+ })
|
|
|
+}
|
|
|
+
|
|
|
+
|
|
|
+
|
|
|
export default fileApis
|