Node.js斷點(diǎn)續(xù)傳的實(shí)現(xiàn)
前言
平常業(yè)務(wù)需求:上傳圖片、Excel等,畢竟幾M的大小可以很快就上傳到服務(wù)器。
針對(duì)于上傳視頻等大文件幾百M(fèi)或者幾G的大小,就需要等待比較長(zhǎng)的時(shí)間。
這就產(chǎn)生了對(duì)應(yīng)的解決方法,對(duì)于大文件上傳時(shí)的暫停、斷網(wǎng)、網(wǎng)絡(luò)較差的情況下, 使用切片+斷點(diǎn)續(xù)傳就能夠很好的應(yīng)對(duì)上述的情況
方案分析
切片
就是對(duì)上傳視頻進(jìn)行切分,具體操作為:
File.slice(start,end):返回新的blob對(duì)象
- 拷貝blob的起始字節(jié)
- 拷貝blob的結(jié)束字節(jié)
斷點(diǎn)續(xù)傳
每次切片上傳之前,請(qǐng)求服務(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;
// 首先請(qǐng)求接口,獲取服務(wù)器是否存在此文件
// count為0則是第一次上傳,count不為0則服務(wù)器存在此文件,返回已上傳的切片數(shù)
count = await handleCancel(files[0]);
// 申明存放切片的數(shù)組對(duì)象
let fileCurrent = [];
// 循環(huán)file文件對(duì)象
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模擬手動(dòng)取消請(qǐng)求
const CancelToken = axios.CancelToken;
const source = CancelToken.source();
// 當(dāng)斷點(diǎn)續(xù)傳時(shí),處理切片數(shù)量,已上傳切片則不需要再次請(qǐng)求上傳
fileCurrent =
count === 0 ? fileCurrent : fileCurrent.slice(count, sectionLength);
// 循環(huán)切片請(qǐng)求接口
for (const [index, item] of fileCurrent.entries()) {
// 模擬請(qǐng)求暫停 || 網(wǎng)絡(luò)斷開
if (index > 90) {
source.cancel("取消請(qǐng)求");
}
// 存入文件相關(guān)信息
// file為切片blob對(duì)象
// 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);
});
}
}
};
// 請(qǐng)求接口,查詢上傳文件是否存在
// count為0表示不存在,count不為0則已上傳對(duì)應(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) => {
// 讀取對(duì)應(yīng)目錄文件buffer
const readFile = fs.readFileSync(item);
// 將讀取的buffer || chunk寫入到stream中
writeStream.write(readFile);
// 寫入完后,清除暫存的切片文件
fs.unlink(item, () => {});
};
// 視頻上傳(切片)
module.exports.video = (req, res) => {
// 創(chuàng)建解析對(duì)象
const form = new formidable.IncomingForm();
// 設(shè)置視頻文件上傳路徑
let dirPath = path.join(__dirname, "video");
form.uploadDir = dirPath;
// 是否保留上傳文件名后綴
form.keepExtensions = true;
// err 錯(cuò)誤對(duì)象 如果解析失敗包含錯(cuò)誤信息
// fields 包含除了二進(jìn)制以外的formData的key-value對(duì)象
// file 對(duì)象類型 上傳文件的信息
form.parse(req, async (err, fields, file) => {
// 獲取上傳文件blob對(duì)象
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: "請(qǐng)繼續(xù)上傳",
count,
});
});
};
邏輯分析
前端
首先請(qǐng)求上傳查詢文件是否第一次上傳,或已存在對(duì)應(yīng)的切片
- 文件第一次上傳,則切片從0開始
- 文件已存在對(duì)應(yīng)的切片,則從切片數(shù)開始請(qǐng)求上傳
循環(huán)切片數(shù)組,對(duì)每塊切片文件進(jìn)行上傳
- 其中使用了模擬手動(dòng)暫停請(qǐng)求,當(dāng)切片數(shù)大于90取消請(qǐng)求
服務(wù)端
接收查詢文件filename,查找臨時(shí)存儲(chǔ)的文件地址,判斷是否存在對(duì)應(yīng)上傳文件
- 從未上傳過此文件,則返回0,切片數(shù)從0開始
- 已上傳過文件,則返回對(duì)應(yīng)切片數(shù)
接收上傳文件切片,文件存入臨時(shí)存儲(chǔ)目錄
- 通過count和total判斷切片是否上傳完畢
- 上傳完畢,創(chuàng)建文件保存目錄,并創(chuàng)建可寫流,進(jìn)行寫入操作
- 提取對(duì)應(yīng)臨時(shí)文件放入數(shù)組,循環(huán)文件目錄數(shù)組,依次讀取并寫入文件buffer
- 寫入完畢,關(guān)閉可寫流。
小結(jié)
以上代碼涉及到具體的業(yè)務(wù)流程會(huì)有所更改或偏差,這只是其中一種具體實(shí)現(xiàn)的方式。
希望這篇文章能對(duì)大家有所幫助,如果有寫的不對(duì)的地方也希望指點(diǎn)一二。
以上代碼地址:https://github.com/Surprise-ling/uploadFiles
到此這篇關(guān)于Node.js斷點(diǎn)續(xù)傳的實(shí)現(xiàn)的文章就介紹到這了,更多相關(guān)Node.js 斷點(diǎn)續(xù)傳內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
nodejs利用ajax實(shí)現(xiàn)網(wǎng)頁(yè)無(wú)刷新上傳圖片實(shí)例代碼
本篇文章主要介紹了nodejs利用ajax實(shí)現(xiàn)網(wǎng)頁(yè)無(wú)刷新上傳圖片實(shí)例代碼,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2017-06-06
node.js文件系統(tǒng)之文件寫入實(shí)例詳解
Node.js和其他語(yǔ)言一樣,也有文件操作,下面這篇文章主要給大家介紹了關(guān)于node.js文件系統(tǒng)之文件寫入的相關(guān)資料,文中通過實(shí)例代碼介紹的非常詳細(xì),需要的朋友可以參考下2023-03-03
node省市區(qū)三級(jí)數(shù)據(jù)性能測(cè)評(píng)實(shí)例分析
這篇文章主要介紹了node省市區(qū)三級(jí)數(shù)據(jù)性能,結(jié)合具體實(shí)例形式評(píng)測(cè)分析了node省市區(qū)三級(jí)數(shù)據(jù)的實(shí)現(xiàn)、改進(jìn)方法與運(yùn)行效率,需要的朋友可以參考下2019-11-11
前端node Session和JWT鑒權(quán)登錄示例詳解
關(guān)于前端鑒權(quán)登錄是比較常見的需求了,本文將從服務(wù)端渲染和前后端分離的不同角度下演示鑒權(quán),為大家介紹前端node Session和JWT鑒權(quán)登錄示例詳解2022-07-07
node.js實(shí)現(xiàn)簡(jiǎn)單爬蟲示例詳解
這篇文章主要為大家介紹了node.js實(shí)現(xiàn)簡(jiǎn)單爬蟲示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-04-04
編譯打包nodejs服務(wù)代碼如何部署到服務(wù)器
這篇文章主要介紹了編譯打包nodejs服務(wù)代碼如何部署到服務(wù)器問題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2023-10-10

