日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學(xué)無先后,達(dá)者為師

網(wǎng)站首頁 編程語言 正文

React+Node實(shí)現(xiàn)大文件分片上傳、斷點(diǎn)續(xù)傳秒傳思路_React

作者:lin嘟嘟嘟 ? 更新時(shí)間: 2022-04-15 編程語言

1、整體思路

  • 將文件切成多個(gè)小的文件;
  • 將切片并行上傳;
  • 所有切片上傳完成后,服務(wù)器端進(jìn)行切片合成;
  • 當(dāng)分片上傳失敗,可以在重新上傳時(shí)進(jìn)行判斷,只上傳上次失敗的部分實(shí)現(xiàn)斷點(diǎn)續(xù)傳;
  • 當(dāng)切片合成為完整的文件,通知客戶端上傳成功;
  • 已經(jīng)傳到服務(wù)器的完整文件,則不需要重新上傳到服務(wù)器,實(shí)現(xiàn)秒傳功能;

2、實(shí)現(xiàn)步驟

2.1 文件切片加密

利用MD5 , MD5 是文件的唯一標(biāo)識,可以利用文件的 MD5 查詢文件的上傳狀態(tài);

讀取進(jìn)度條進(jìn)度,生成MD5:

實(shí)現(xiàn)結(jié)果:

實(shí)現(xiàn)代碼如下:

const md5File = (file) => {
? ? return new Promise((resolve, reject) => {
? ? ? // 文件截取
? ? ? let blobSlice = File.prototype.slice || File.prototype.mozSlice || File.prototype.webkitSlice,
? ? ? ? chunkSize = file?.size / 100,
? ? ? ? chunks = 100,
? ? ? ? currentChunk = 0,
? ? ? ? spark = new SparkMD5.ArrayBuffer(),
? ? ? ? fileReader = new FileReader();

? ? ? fileReader.onload = function (e) {
? ? ? ? console.log('read chunk nr', currentChunk + 1, 'of', chunks);
? ? ? ? spark.append(e.target.result);
? ? ? ? currentChunk += 1;

? ? ? ? if (currentChunk < chunks) {
? ? ? ? ? loadNext();
? ? ? ? } else {
? ? ? ? ? let result = spark.end()
? ? ? ? ? resolve(result)
? ? ? ? }
? ? ? };

? ? ? fileReader.onerror = function () {
? ? ? ? message.error('文件讀取錯(cuò)誤')
? ? ? };

? ? ? const loadNext = () => {
? ? ? ? const start = currentChunk * chunkSize,
? ? ? ? ? end = ((start + chunkSize) >= file.size) ? file.size : start + chunkSize;

? ? ? ? // 文件切片
? ? ? ? fileReader.readAsArrayBuffer(blobSlice.call(file, start, end));
? ? ? ? // 檢查進(jìn)度條
? ? ? ? dispatch({ type: 'check', checkPercent: currentChunk + 1 })
? ? ? }

? ? ? loadNext();
? ? })
? }

2.2 查詢上傳文件狀態(tài)

利用當(dāng)前md5去查詢服務(wù)器創(chuàng)建的md5文件夾是否存在,如果存在則返回該目錄下的所有分片;

前端只需要拿MD5和文件名去請求后端,這里就不在列出來;
node端代碼邏輯:

app.get('/check/file', (req, resp) => {
? let query = req.query
? let fileName = query.fileName
? let fileMd5Value = query.fileMd5Value
? // 獲取文件Chunk列表
? getChunkList(
? ? ? path.join(uploadDir, fileName),
? ? ? path.join(uploadDir, fileMd5Value),
? ? ? data => {
? ? ? ? ? resp.send(data)
? ? ? }
? )
})

// 獲取文件Chunk列表
async function getChunkList(filePath, folderPath, callback) {
? let isFileExit = await isExist(filePath)
? let result = {}
? // 如果文件已在存在, 不用再繼續(xù)上傳, 真接秒傳
? if (isFileExit) {
? ? ? result = {
? ? ? ? ? stat: 1,
? ? ? ? ? file: {
? ? ? ? ? ? ? isExist: true,
? ? ? ? ? ? ? name: filePath
? ? ? ? ? },
? ? ? ? ? desc: 'file is exist'
? ? ? }
? } else {
? ? ? let isFolderExist = await isExist(folderPath)
? ? ? // 如果文件夾(md5值后的文件)存在, 就獲取已經(jīng)上傳的塊
? ? ? let fileList = []
? ? ? if (isFolderExist) {
? ? ? ? ? fileList = await listDir(folderPath)
? ? ? }
? ? ? result = {
? ? ? ? ? stat: 1,
? ? ? ? ? chunkList: fileList,
? ? ? ? ? desc: 'folder list'
? ? ? }
? }
? callback(result)
}

2.3 秒傳

如果上傳的當(dāng)前文件已經(jīng)存在服務(wù)器目錄,則秒傳;

服務(wù)器端代碼已給出,前端根據(jù)返回的接口做判斷;

if (data?.file) {
? message.success('文件已秒傳')
? return
}

實(shí)現(xiàn)效果:

?

2.4 上傳分片、斷點(diǎn)續(xù)傳

檢查本地切片和服務(wù)器對應(yīng)的切片,如果沒有當(dāng)前切片則上傳,實(shí)現(xiàn)斷點(diǎn)續(xù)傳;
同步并發(fā)上傳所有的切片,維護(hù)上傳進(jìn)度條狀態(tài);
前端代碼:

/**
? ?* 上傳chunk
? ?* @param {*} fileMd5Value?
? ?* @param {*} chunkList?
? ?*/
? async function checkAndUploadChunk(file, fileMd5Value, chunkList) {
? ? let chunks = Math.ceil(file.size / chunkSize)
? ? const requestList = []
? ? for (let i = 0; i < chunks; i++) {
? ? ? let exit = chunkList.indexOf(i + "") > -1
? ? ? // 如果不存在,則上傳
? ? ? if (!exit) {
? ? ? ? requestList.push(upload({ i, file, fileMd5Value, chunks }))
? ? ? }
? ? }

? ? // 并發(fā)上傳
? ? if (requestList?.length) {
? ? ? await Promise.all(requestList)
? ? }
? }

?? ?// 上傳chunk
? function upload({ i, file, fileMd5Value, chunks }) {
? ? current = 0
? ? //構(gòu)造一個(gè)表單,F(xiàn)ormData是HTML5新增的
? ? let end = (i + 1) * chunkSize >= file.size ? file.size : (i + 1) * chunkSize
? ? let form = new FormData()
? ? form.append("data", file.slice(i * chunkSize, end)) //file對象的slice方法用于切出文件的一部分
? ? form.append("total", chunks) //總片數(shù)
? ? form.append("index", i) //當(dāng)前是第幾片 ? ??
? ? form.append("fileMd5Value", fileMd5Value)
? ? return axios({
? ? ? method: 'post',
? ? ? url: BaseUrl + "/upload",
? ? ? data: form
? ? }).then(({ data }) => {
? ? ? if (data.stat) {
? ? ? ? current = current + 1
? ? ? ? const uploadPercent = Math.ceil((current / chunks) * 100)
? ? ? ? dispatch({ type: 'upload', uploadPercent })
? ? ? }
? ? })
? }

Node端代碼:

app.all('/upload', (req, resp) => {
? const form = new formidable.IncomingForm({
? ? ? uploadDir: 'nodeServer/tmp'
? })
? form.parse(req, function(err, fields, file) {
? ? ? let index = fields.index
? ? ? let fileMd5Value = fields.fileMd5Value
? ? ? let folder = path.resolve(__dirname, 'nodeServer/uploads', fileMd5Value)
? ? ? folderIsExit(folder).then(val => {
? ? ? ? ? let destFile = path.resolve(folder, fields.index)
? ? ? ? ? copyFile(file.data.path, destFile).then(
? ? ? ? ? ? ? successLog => {
? ? ? ? ? ? ? ? ? resp.send({
? ? ? ? ? ? ? ? ? ? ? stat: 1,
? ? ? ? ? ? ? ? ? ? ? desc: index
? ? ? ? ? ? ? ? ? })
? ? ? ? ? ? ? },
? ? ? ? ? ? ? errorLog => {
? ? ? ? ? ? ? ? ? resp.send({
? ? ? ? ? ? ? ? ? ? ? stat: 0,
? ? ? ? ? ? ? ? ? ? ? desc: 'Error'
? ? ? ? ? ? ? ? ? })
? ? ? ? ? ? ? }
? ? ? ? ? )
? ? ? })
? })

實(shí)現(xiàn)效果:

存儲形式:

2.5 合成分片還原完整文件

當(dāng)所有的分片上傳完成,前端通知服務(wù)器端分片上傳完成,準(zhǔn)備合成;

前端代碼:

? /**
? ?* 所有的分片上傳完成,準(zhǔn)備合成
? ?* @param {*} file?
? ?* @param {*} fileMd5Value?
? ?*/
? function notifyServer(file, fileMd5Value) {
? ? let url = BaseUrl + '/merge?md5=' + fileMd5Value + "&fileName=" + file.name + "&size=" + file.size
? ? axios.get(url).then(({ data }) => {
? ? ? if (data.stat) {
? ? ? ? message.success('上傳成功')
? ? ? } else {
? ? ? ? message.error('上傳失敗')
? ? ? }
? ? })
? }

Node端代碼:

// 合成
app.all('/merge', (req, resp) => {
? let query = req.query
? let md5 = query.md5
? let fileName = query.fileName
? console.log(md5, fileName)
? mergeFiles(path.join(uploadDir, md5), uploadDir, fileName)
? resp.send({
? ? ? stat: 1
? })
})


// 合并文件
async function mergeFiles(srcDir, targetDir, newFileName) {
? let fileArr = await listDir(srcDir)
? fileArr.sort((x,y) => {
? ? ? return x-y;
? })
? // 把文件名加上文件夾的前綴
? for (let i = 0; i < fileArr.length; i++) {
? ? ? fileArr[i] = srcDir + '/' + fileArr[i]
? }
? concat(fileArr, path.join(targetDir, newFileName), () => {
? ? ? console.log('合成成功!')
? })
}

請求實(shí)現(xiàn):

合成文件效果:

3、總結(jié)

將文件切片,并發(fā)上傳切片,切片合成完整文件,實(shí)現(xiàn)分片上傳;
使用MD5標(biāo)識文件夾,得到唯一標(biāo)識;
分片上傳前通過文件 MD5 查詢已上傳切片列表,上傳時(shí)只上傳未上傳過的切片,實(shí)現(xiàn)斷點(diǎn)續(xù)傳;
檢查當(dāng)前上傳文件,如果已存在服務(wù)器,則不需要再次上傳,實(shí)現(xiàn)秒傳;

4、后續(xù)擴(kuò)展與思考

使用時(shí)間切片計(jì)算hash

當(dāng)文件過大時(shí)需要計(jì)算很久的hash,頁面不能做其他的操作,所以考慮使用React-Fiber的架構(gòu)理念,利用瀏覽器空閑時(shí)間去計(jì)算hash。考慮使用window.requestIdleCallback()函數(shù);

請求并發(fā)控制

假如一個(gè)文件過大,就會切割成許多的碎片,一次性發(fā)幾百個(gè)請求,這顯然是不行的;所以要考慮請求并發(fā)數(shù)控制;

5、源碼

地址:https://github.com/linhexs/file-upload.git

原文鏈接:https://juejin.cn/post/7055474765611401253

欄目分類
最近更新