Node.js實(shí)現(xiàn)大文件斷點(diǎn)續(xù)傳示例詳解
前言
平常業(yè)務(wù)需求:上傳圖片、Excel等,畢竟幾M的大小可以很快就上傳到服務(wù)器。
針對于上傳視頻等大文件幾百M(fèi)或者幾G的大小,就需要等待比較長的時(shí)間。
這就產(chǎn)生了對應(yīng)的解決方法,對于大文件上傳時(shí)的暫停、斷網(wǎng)、網(wǎng)絡(luò)較差的情況下, 使用切片+斷點(diǎn)續(xù)傳就能夠很好的應(yīng)對上述的情況,
方案分析
切片
就是對上傳視頻進(jìn)行切分,具體操作為:
File.slice(start,end):返回新的blob對象
- 拷貝blob的起始字節(jié)
- 拷貝blob的結(jié)束字節(jié)
斷點(diǎn)續(xù)傳
- 每次切片上傳之前,請求服務(wù)器接口,讀取相同文件的已上傳切片數(shù)
- 上傳的是新文件,服務(wù)端則返回0,否則返回已上傳切片數(shù)
具體解決流程
該demo提供關(guān)鍵點(diǎn)思路及方法,其他功能如:文件限制,lastModifiedDate校驗(yàn)文件重復(fù)性,緩存文件定期清除等功能擴(kuò)展都可以在此代碼基礎(chǔ)上添加。
html 部分
<input class="video" type="file" /> <button type="submit" onclick="handleVideo(event, '.video', 'video')"> 提交 </button>
script 部分
let count = 0; // 記錄需要上傳的文件下標(biāo) const handleVideo = async (event, name, url) => { // 阻止瀏覽器默認(rèn)表單事件 event.preventDefault(); let currentSize = document.querySelector("h2"); let files = document.querySelector(name).files; // 默認(rèn)切片數(shù)量 const sectionLength = 100; // 首先請求接口,獲取服務(wù)器是否存在此文件 // count為0則是第一次上傳,count不為0則服務(wù)器存在此文件,返回已上傳的切片數(shù) count = await handleCancel(files[0]); // 申明存放切片的數(shù)組對象 let fileCurrent = []; // 循環(huán)file文件對象 for (const file of [...files]) { // 得出每個(gè)切片的大小 let itemSize = Math.ceil(file.size / sectionLength); // 循環(huán)文件size,文件blob存入數(shù)組 let current = 0; for (current; current < file.size; current += itemSize) { fileCurrent.push({ file: file.slice(current, current + itemSize) }); } // axios模擬手動取消請求 const CancelToken = axios.CancelToken; const source = CancelToken.source(); // 當(dāng)斷點(diǎn)續(xù)傳時(shí),處理切片數(shù)量,已上傳切片則不需要再次請求上傳 fileCurrent = count === 0 ? fileCurrent : fileCurrent.slice(count, sectionLength); // 循環(huán)切片請求接口 for (const [index, item] of fileCurrent.entries()) { // 模擬請求暫停 || 網(wǎng)絡(luò)斷開 if (index > 90) { source.cancel("取消請求"); } // 存入文件相關(guān)信息 // file為切片blob對象 // filename為文件名 // index為當(dāng)前切片數(shù) // total為總切片數(shù) let formData = new FormData(); formData.append("file", item.file); formData.append("filename", file.name); formData.append("total", sectionLength); formData.append("index", index + count + 1); await axios({ url: `http://localhost:8080/${url}`, method: "POST", data: formData, cancelToken: source.token, }) .then((response) => { // 返回?cái)?shù)據(jù)顯示進(jìn)度 currentSize.innerHTML = `進(jìn)度${response.data.size}%`; }) .catch((err) => { console.log(err); }); } } }; // 請求接口,查詢上傳文件是否存在 // count為0表示不存在,count不為0則已上傳對應(yīng)切片數(shù) const handleCancel = (file) => { return axios({ method: "post", url: "http://localhost:8080/getSize", headers: { "Content-Type": "application/json; charset = utf-8" }, data: { fileName: file.name, }, }) .then((res) => { return res.data.count; }) .catch((err) => { console.log(err); }); };
node服務(wù)端 部分
// 使用express構(gòu)建服務(wù)器api const express = require("express"); // 引入上傳文件邏輯代碼 const upload = require("./upload_file"); // 處理所有響應(yīng),設(shè)置跨域 app.all("*", (req, res, next) => { res.header("Access-Control-Allow-Origin", "*"); res.header("Access-Control-Allow-Headers", "X-Requested-With"); res.header("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS"); res.header("Access-Control-Allow-Headers", "Content-Type, X-Requested-With "); res.header("X-Powered-By", " 3.2.1"); res.header("Content-Type", "application/json;charset=utf-8"); next(); }); const app = express(); app.use(bodyParser.json({ type: "application/*+json" })); // 視頻上傳(查詢當(dāng)前切片數(shù)) app.post("/getSize", upload.getSize); // 視頻上傳接口 app.post("/video", upload.video); // 開啟本地端口偵聽 app.listen(8080);
- upload_file
// 文件上傳模塊 const formidable = require("formidable"); // 文件系統(tǒng)模塊 const fs = require("fs"); // 系統(tǒng)路徑模塊 const path = require("path"); // 操作寫入文件流 const handleStream = (item, writeStream) => { // 讀取對應(yīng)目錄文件buffer const readFile = fs.readFileSync(item); // 將讀取的buffer || chunk寫入到stream中 writeStream.write(readFile); // 寫入完后,清除暫存的切片文件 fs.unlink(item, () => {}); }; // 視頻上傳(切片) module.exports.video = (req, res) => { // 創(chuàng)建解析對象 const form = new formidable.IncomingForm(); // 設(shè)置視頻文件上傳路徑 let dirPath = path.join(__dirname, "video"); form.uploadDir = dirPath; // 是否保留上傳文件名后綴 form.keepExtensions = true; // err 錯(cuò)誤對象 如果解析失敗包含錯(cuò)誤信息 // fields 包含除了二進(jìn)制以外的formData的key-value對象 // file 對象類型 上傳文件的信息 form.parse(req, async (err, fields, file) => { // 獲取上傳文件blob對象 let files = file.file; // 獲取當(dāng)前切片index let index = fields.index; // 獲取總切片數(shù) let total = fields.total; // 獲取文件名 let filename = fields.filename; // 重寫上傳文件名,設(shè)置暫存目錄 let url = dirPath + "/" + filename.split(".")[0] + `_${index}.` + filename.split(".")[1]; try { // 同步修改上傳文件名 fs.renameSync(files.path, url); console.log(url); // 異步處理 setTimeout(() => { // 判斷是否是最后一個(gè)切片上傳完成,拼接寫入全部視頻 if (index === total) { // 同步創(chuàng)建新目錄,用以存放完整視頻 let newDir = __dirname + `/uploadFiles/${Date.now()}`; // 創(chuàng)建目錄 fs.mkdirSync(newDir); // 創(chuàng)建可寫流,用以寫入文件 let writeStream = fs.createWriteStream(newDir + `/${filename}`); let fsList = []; // 取出所有切片文件,放入數(shù)組 for (let i = 0; i < total; i++) { const fsUrl = dirPath + "/" + filename.split(".")[0] + `_${i + 1}.` + filename.split(".")[1]; fsList.push(fsUrl); } // 循環(huán)切片文件數(shù)組,進(jìn)行stream流的寫入 for (let item of fsList) { handleStream(item, writeStream); } // 全部寫入,關(guān)閉stream寫入流 writeStream.end(); } }, 100); } catch (e) { console.log(e); } res.send({ code: 0, msg: "上傳成功", size: index, }); }); }; // 獲取文件切片數(shù) module.exports.getSize = (req, res) => { let count = 0; req.setEncoding("utf8"); req.on("data", function (data) { let name = JSON.parse(data); let dirPath = path.join(__dirname, "video"); // 計(jì)算已上傳的切片文件個(gè)數(shù) let files = fs.readdirSync(dirPath); files.forEach((item, index) => { let url = name.fileName.split(".")[0] + `_${index + 1}.` + name.fileName.split(".")[1]; if (files.includes(url)) { ++count; } }); res.send({ code: 0, msg: "請繼續(xù)上傳", count, }); }); };
邏輯分析
前端
首先請求上傳查詢文件是否第一次上傳,或已存在對應(yīng)的切片
- 文件第一次上傳,則切片從0開始
- 文件已存在對應(yīng)的切片,則從切片數(shù)開始請求上傳
循環(huán)切片數(shù)組,對每塊切片文件進(jìn)行上傳
- 其中使用了模擬手動暫停請求,當(dāng)切片數(shù)大于90取消請求
服務(wù)端
接收查詢文件filename,查找臨時(shí)存儲的文件地址,判斷是否存在對應(yīng)上傳文件
- 從未上傳過此文件,則返回0,切片數(shù)從0開始
- 已上傳過文件,則返回對應(yīng)切片數(shù)
接收上傳文件切片,文件存入臨時(shí)存儲目錄
- 通過count和total判斷切片是否上傳完畢
- 上傳完畢,創(chuàng)建文件保存目錄,并創(chuàng)建可寫流,進(jìn)行寫入操作
- 提取對應(yīng)臨時(shí)文件放入數(shù)組,循環(huán)文件目錄數(shù)組,依次讀取并寫入文件buffer
- 寫入完畢,關(guān)閉可寫流。
小結(jié)
以上代碼涉及到具體的業(yè)務(wù)流程會有所更改或偏差,這只是其中一種具體實(shí)現(xiàn)的方式。
希望這篇文章能對大家有所幫助,如果有寫的不對的地方也希望指點(diǎn)一二,更多關(guān)于Node.js大文件斷點(diǎn)續(xù)傳的資料請關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
node微信開發(fā)之獲取access_token+自定義菜單
這篇文章主要介紹了node微信開發(fā)之獲取access_token+自定義菜單,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2019-03-03Node.js之HTTP服務(wù)端和客戶端實(shí)現(xiàn)方式
這篇文章主要介紹了Node.js之HTTP服務(wù)端和客戶端實(shí)現(xiàn)方式,具有很好的參考價(jià)值,希望對大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2024-09-09node.js express框架實(shí)現(xiàn)文件上傳與下載功能實(shí)例詳解
這篇文章主要介紹了node.js express框架實(shí)現(xiàn)文件上傳與下載功能,結(jié)合具體實(shí)例形式詳細(xì)分析了node.js express框架針對文件上傳與下載的前后臺相關(guān)實(shí)現(xiàn)技巧,需要的朋友可以參考下2019-10-10詳解Node.js中exports和module.exports的區(qū)別
這篇文章主要介紹了詳解Node.js中exports和module.exports的區(qū)別,小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧2017-04-04Node 使用express-http-proxy 做api網(wǎng)關(guān)的實(shí)現(xiàn)
這篇文章主要介紹了Node 使用express-http-proxy 做api網(wǎng)關(guān)的實(shí)現(xiàn),文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2020-10-10