Node中文件斷點(diǎn)續(xù)傳原理和方法總結(jié)
導(dǎo)語:之前做過一個(gè)小項(xiàng)目,其中用到了文件上傳,在大文件上面使用了斷點(diǎn)續(xù)傳,降低了服務(wù)器方面的壓力,現(xiàn)在就這個(gè)開發(fā)經(jīng)驗(yàn)做一個(gè)細(xì)致的總結(jié)。
原理介紹
這里先介紹一下文件上傳的原理,幫助理清這個(gè)頭緒。
普通上傳
一般網(wǎng)站上都是普通上傳的比較多,大多數(shù)都是上傳一些用戶的頭像,用戶的動(dòng)態(tài)評論附帶圖片什么的,所以先來說一下這個(gè)的原理。
- 用戶選擇文件后,js檢測文件大小是否超出限制和格式是否正確;
- 檢查后使用ajax提交請求,服務(wù)端也進(jìn)行二次驗(yàn)證后儲(chǔ)存到服務(wù)器;
- 后端返回文件地址到前端,渲染頁面數(shù)據(jù);
大文件上傳
用戶選擇文件后,js檢測文件大小是否超出限制和格式是否正確;
根據(jù)文件大小,使用file.slice方法進(jìn)行文件分割;
使用SparkMD5和FileReaderAPI生成文件唯一的md5值;
使用ajax提交請求,服務(wù)端收到后返回文件在服務(wù)器的信息;
- 如果存在這個(gè)md5值的文件夾,則返回文件夾里面上傳了多少文件;
- 不存在則新建一個(gè)這個(gè)md5值的文件夾,返回空內(nèi)容;
前端收到信息后,根據(jù)返回信息作出判斷;
- 如果返回的文件長度等于切片的總長度,則請求合并文件;
- 如果返回的文件長度小于切片的總長度,則開始上傳對應(yīng)的切片文件,直至上傳完最后一個(gè)切片再請求合并文件;
后端收到合并的請求后,對對應(yīng)的md5值的文件夾里面的文件進(jìn)行合并,返回文件地址;
前端收到文件地址后,渲染頁面數(shù)據(jù);
斷點(diǎn)續(xù)傳
這個(gè)的意思就是文件上傳過程中,如果遇到不可抗力,比如網(wǎng)絡(luò)中斷,服務(wù)器異常,或者其他原因?qū)е律蟼髦袛啵?/p>
下次再次上傳時(shí)候,服務(wù)端根據(jù)這個(gè)文件的md5值找出上傳了多少,還剩下多少未上傳,發(fā)送給客戶端,客戶端收到后繼續(xù)對未上傳的進(jìn)行上傳,上傳完成后合并文件并返回地址。
這樣就避免了文件重復(fù)上傳,浪費(fèi)服務(wù)器空間使用,節(jié)約服務(wù)器資源,而且速度比上傳一個(gè)大文件更快,更高效。
方法總結(jié)
接下來根據(jù)上面的邏輯原理分析步驟,進(jìn)行代碼功能實(shí)現(xiàn)。
普通文件
本小節(jié)講述普通文件的上傳,包括前端部分和后端部分。
前端部分
html部分
先來建立個(gè)小房子
<div class="upload">
<h3>普通上傳</h3>
<form>
<div class="upload-file">
<label for="file">請選擇文件</label>
<input type="file" name="file" id="file" accept="image/*">
</div>
<div class="upload-progress">
當(dāng)前進(jìn)度:
<p>
<span style="width: 0;" id="current"></span>
</p>
</div>
<div class="upload-link">
文件地址:<a id="links" href="javascript:void();" rel="external nofollow" target="_blank">文件鏈接</a>
</div>
</form>
</div>
<div class="upload">
<h3>大文件上傳</h3>
<form>
<div class="upload-file">
<label for="file">請選擇文件</label>
<input type="file" name="file" id="big-file" accept="application/*">
</div>
<div class="upload-progress">
當(dāng)前進(jìn)度:
<p>
<span style="width: 0;" id="big-current"></span>
</p>
</div>
<div class="upload-link">
文件地址:<a id="big-links" href="" target=" rel="external nofollow" _blank">文件鏈接</a>
</div>
</form>
</div>引入axios和spark-md5兩個(gè)js文件。
<script src="https://cdn.bootcdn.net/ajax/libs/axios/0.21.1/axios.min.js"></script> <script src="https://cdn.bootcdn.net/ajax/libs/spark-md5/3.0.0/spark-md5.min.js"></script>
css部分
來裝飾一下這個(gè)房子。
body {
margin: 0;
font-size: 16px;
background: #f8f8f8;
}
h1,h2,h3,h4,h5,h6,p {
margin: 0;
}
/* * {
outline: 1px solid pink;
} */
.upload {
box-sizing: border-box;
margin: 30px auto;
padding: 15px 20px;
width: 500px;
height: auto;
border-radius: 15px;
background: #fff;
}
.upload h3 {
font-size: 20px;
line-height: 2;
text-align: center;
}
.upload .upload-file {
position: relative;
margin: 30px auto;
}
.upload .upload-file label {
display: flex;
justify-content: center;
align-items: center;
width: 100%;
height: 150px;
border: 1px dashed #ccc;
}
.upload .upload-file input {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
opacity: 0;
}
.upload-progress {
display: flex;
align-items: center;
}
.upload-progress p {
position: relative;
display: inline-block;
flex: 1;
height: 15px;
border-radius: 10px;
background: #ccc;
overflow: hidden;
}
.upload-progress p span {
position: absolute;
left: 0;
top: 0;
width: 0;
height: 100%;
background: linear-gradient(to right bottom, rgb(163, 76, 76), rgb(231, 73, 52));
transition: all .4s;
}
.upload-link {
margin: 30px auto;
}
.upload-link a {
text-decoration: none;
color: rgb(6, 102, 192);
}
@media all and (max-width: 768px) {
.upload {
width: 300px;
}
}js部分
最后加上互動(dòng)效果。
// 獲取元素
const file = document.querySelector('#file');
let current = document.querySelector('#current');
let links = document.querySelector('#links');
let baseUrl = 'http://localhost:3000';
// 監(jiān)聽文件事件
file.addEventListener('change', (e) => {
console.log(e.target.files);
let file = e.target.files[0];
if (file.type.indexOf('image') == -1) {
return alert('文件格式只能是圖片!');
}
if ((file.size / 1000) > 100) {
return alert('文件不能大于100KB!');
}
links.href = '';
file.value = '';
this.upload(file);
}, false);
// 上傳文件
async function upload (file) {
let formData = new FormData();
formData.append('file', file);
let data = await axios({
url: baseUrl+'/upload',
method: 'post',
data: formData,
onUploadProgress: function(progressEvent) {
current.style.width = Math.round(progressEvent.loaded / progressEvent.total * 100) + '%';
}
});
if (data.data.code == 200) {
links.href = data.data.data.url;
} else {
alert('上傳失??!')
}
}后端部分
打開上次的文件夾demo,先來下載安裝一個(gè)處理文件的包formidable,然后開始處理上傳的文件啦!
新建一個(gè)文件夾,別忘了在app.js引入新的文件。
const upload = require('./upload/index');
app.use(express.static(path.join(__dirname, 'public')));
app.use('/file', express.static(path.join(__dirname, 'static')));
app.use('/upload', upload);下面是文件層級圖。
-- static
-- big
-- doc
-- temp
-- upload
- index.js
- util.js
-- app.jsconst express = require('express');
const Router = express.Router();
const formidable = require('formidable');
const path = require('path');
const fs = require('fs');
const baseUrl = 'http://localhost:3000/file/doc/';
const dirPath = path.join(__dirname, '../static/')
// 普通文件上傳
Router.post('/', (req, res) => {
let form = formidable({
multiples: true,
uploadDir: dirPath+'temp/'
})
form.parse(req, (err,fields, files)=> {
if (err) {
return res.json(err);
}
let newPath = dirPath+'doc/'+files.file.name;
fs.rename(files.file.path, newPath, function(err) {
if (err) {
return res.json(err);
}
return res.json({
code: 200,
msg: 'get_succ',
data: {
url: baseUrl + files.file.name
}
})
})
})
});
module.exports = Router;大文件
這個(gè)大文件斷點(diǎn)續(xù)傳,其實(shí)就是在之前文件上傳的基礎(chǔ)上進(jìn)一步擴(kuò)展而來的。所以前端部分的結(jié)構(gòu)和樣式一樣,就是方法不一樣。
前端部分
這里主要是方法介紹。
獲取元素
const bigFile = document.querySelector('#big-file');
let bigCurrent = document.querySelector('#big-current');
let bigLinks = document.querySelector('#big-links');
let fileArr = [];
let md5Val = '';
let ext = '';檢測文件
bigFile.addEventListener('change', (e) => {
let file = e.target.files[0];
if (file.type.indexOf('application') == -1) {
return alert('文件格式只能是文檔應(yīng)用!');
}
if ((file.size / (1000*1000)) > 100) {
return alert('文件不能大于100MB!');
}
this.uploadBig(file);
}, false);切割文件
// 切割文件
function sliceFile (file) {
const files = [];
const chunkSize = 128*1024;
for (let i = 0; i < file.size; i+=chunkSize) {
const end = i + chunkSize >= file.size ? file.size : i + chunkSize;
let currentFile = file.slice(i, (end > file.size ? file.size : end));
files.push(currentFile);
}
return files;
}獲取文件的md5值
// 獲取文件md5值
function md5File (files) {
const spark = new SparkMD5.ArrayBuffer();
let fileReader;
for (var i = 0; i < files.length; i++) {
fileReader = new FileReader();
fileReader.readAsArrayBuffer(files[i]);
}
return new Promise((resolve) => {
fileReader.onload = function(e) {
spark.append(e.target.result);
if (i == files.length) {
resolve(spark.end());
}
}
})
}上傳分片文件
async function uploadSlice (chunkIndex = 0) {
let formData = new FormData();
formData.append('file', fileArr[chunkIndex]);
let data = await axios({
url: `${baseUrl}/upload/big?type=upload¤t=${chunkIndex}&md5Val=${md5Val}&total=${fileArr.length}`,
method: 'post',
data: formData,
})
if (data.data.code == 200) {
if (chunkIndex < fileArr.length -1 ){
bigCurrent.style.width = Math.round((chunkIndex+1) / fileArr.length * 100) + '%';
++chunkIndex;
uploadSlice(chunkIndex);
} else {
mergeFile();
}
}
}合并文件
async function mergeFile () {
let data = await axios.post(`${baseUrl}/upload/big?type=merge&md5Val=${md5Val}&total=${fileArr.length}&ext=${ext}`);
if (data.data.code == 200) {
alert('上傳成功!');
bigCurrent.style.width = '100%';
bigLinks.href = data.data.data.url;
} else {
alert(data.data.data.info);
}
}后端部分
獲取參數(shù)
獲取上傳參數(shù)并且作判斷。
let type = req.query.type;
let md5Val = req.query.md5Val;
let total = req.query.total;
let bigDir = dirPath + 'big/';
let typeArr = ['check', 'upload', 'merge'];
if (!type) {
return res.json({
code: 101,
msg: 'get_fail',
data: {
info: '上傳類型不能為空!'
}
})
}
if (!md5Val) {
return res.json({
code: 101,
msg: 'get_fail',
data: {
info: '文件md5值不能為空!'
}
})
}
if (!total) {
return res.json({
code: 101,
msg: 'get_fail',
data: {
info: '文件切片數(shù)量不能為空!'
}
})
}
if (!typeArr.includes(type)) {
return res.json({
code: 101,
msg: 'get_fail',
data: {
info: '上傳類型錯(cuò)誤!'
}
})
}類型是檢測
let filePath = `${bigDir}${md5Val}`;
fs.readdir(filePath, (err, data) => {
if (err) {
fs.mkdir(filePath, (err) => {
if (err) {
return res.json({
code: 101,
msg: 'get_fail',
data: {
info: '獲取失敗!',
err
}
})
} else {
return res.json({
code: 200,
msg: 'get_succ',
data: {
info: '獲取成功!',
data: {
type: 'write',
chunk: [],
total: 0
}
}
})
}
})
} else {
return res.json({
code: 200,
msg: 'get_succ',
data: {
info: '獲取成功!',
data: {
type: 'read',
chunk: data,
total: data.length
}
}
})
}
})類型是上傳的
let current = req.query.current;
if (!current) {
return res.json({
code: 101,
msg: 'get_fail',
data: {
info: '文件當(dāng)前分片值不能為空!'
}
})
}
let form = formidable({
multiples: true,
uploadDir: `${dirPath}big/${md5Val}/`,
})
form.parse(req, (err,fields, files)=> {
if (err) {
return res.json(err);
}
let newPath = `${dirPath}big/${md5Val}/${current}`;
fs.rename(files.file.path, newPath, function(err) {
if (err) {
return res.json(err);
}
return res.json({
code: 200,
msg: 'get_succ',
data: {
info: 'upload success!'
}
})
})
})類型是合并的
let ext = req.query.ext;
if (!ext) {
return res.json({
code: 101,
msg: 'get_fail',
data: {
info: '文件后綴不能為空!'
}
})
}
let oldPath = `${dirPath}big/${md5Val}`;
let newPath = `${dirPath}doc/${md5Val}.${ext}`;
let data = await mergeFile(oldPath, newPath);
if (data.code == 200) {
return res.json({
code: 200,
msg: 'get_succ',
data: {
info: '文件合并成功!',
url: `${baseUrl}${md5Val}.${ext}`
}
})
} else {
return res.json({
code: 101,
msg: 'get_fail',
data: {
info: '文件合并失敗!',
err: data.data.error
}
})
}在合并這個(gè)功能里面主要使用的是fs的createWriteStream以及createReadStream方法實(shí)現(xiàn)的。
合并文件
const fs = require('fs');
function mergeFile (filePath, newPath) {
return new Promise((resolve, reject) => {
let files = fs.readdirSync(filePath),
newFile = fs.createWriteStream(newPath);
let filesArr = arrSort(files).reverse();
main();
function main (index = 0) {
let currentFile = filePath + '/'+filesArr[index];
let stream = fs.createReadStream(currentFile);
stream.pipe(newFile, {end: false});
stream.on('end', function () {
if (index < filesArr.length - 1) {
index++;
main(index);
} else {
resolve({code: 200});
}
})
stream.on('error', function (error) {
reject({code: 102, data:{error}})
})
}
})
}文件排序
function arrSort (arr) {
for (let i = 0; i < arr.length; i++) {
for (let j = 0; j < arr.length; j++) {
if (Number(arr[i]) >= Number(arr[j])) {
let t = arr[i];
arr[i] = arr[j];
arr[j] = t;
}
}
}
return arr;
}實(shí)戰(zhàn)演練
現(xiàn)在方法也寫好了,來測試下是否OK。
這里準(zhǔn)備了兩個(gè)文件,來分別測試兩個(gè)功能。

普通文件
這個(gè)是普通文件上傳界面

上傳成功后:

后端返回內(nèi)容:

打開文件地址預(yù)覽:

可以看到成功了!
大文件
這個(gè)是大文件文件上傳界面

上傳成功后:

這個(gè)是某個(gè)分片文件正在上傳:

這個(gè)是文件分片上傳后合并返回的內(nèi)容:

打開文件地址預(yù)覽:

再次上傳發(fā)現(xiàn)很快返回文件地址:


這個(gè)是nodejs目錄截圖,可以看到文件的分片保存完好,合并的也很好。


這個(gè)文件上傳和斷點(diǎn)續(xù)傳就講到這里,當(dāng)然,我上面所說的方法只是一種,作為參考。如果你有更好的方法,請聯(lián)系我。
到此這篇關(guān)于Node中文件斷點(diǎn)續(xù)傳原理和方法總結(jié)的文章就介紹到這了,更多相關(guān)Node文件斷點(diǎn)續(xù)傳內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
koa2 數(shù)據(jù)api中間件設(shè)計(jì)模型的實(shí)現(xiàn)方法
這篇文章主要介紹了koa2 數(shù)據(jù)api中間件設(shè)計(jì)模型的實(shí)現(xiàn)方法,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2020-07-07
基于nodejs的微信JS-SDK簡單應(yīng)用實(shí)現(xiàn)
這篇文章主要介紹了基于nodejs的微信JS-SDK簡單應(yīng)用實(shí)現(xiàn),小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧2019-05-05
node.js+postman實(shí)現(xiàn)模擬HTTP服務(wù)器與客戶端交互
本文主要介紹了node.js+postman實(shí)現(xiàn)模擬HTTP服務(wù)器與客戶端交互,文中通過示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2021-07-07
node實(shí)現(xiàn)定時(shí)發(fā)送郵件的示例代碼
本篇文章主要介紹了node實(shí)現(xiàn)定時(shí)發(fā)送郵件的示例代碼,小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧2017-08-08
Node.js使用多進(jìn)程提高任務(wù)執(zhí)行效率
在Node.JS中使用多進(jìn)程非常簡單,合理使用多進(jìn)程,可以解放硬件的能力,讓軟件的運(yùn)行效率得到肉眼可見的提升。本文詳細(xì)講解了Node.js使用多進(jìn)程提高任務(wù)執(zhí)行效率的方法,對大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2022-09-09
淺談Node.js輕量級Web框架Express4.x使用指南
本篇文章主要介紹了淺談Node.js輕量級Web框架Express4.x使用指南,小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧2017-05-05

