Node中檔案斷點續傳原理和方法總結
導語:之前做過一個小專案,其中用到了檔案上傳,在大檔案上面使用了斷點續傳,降低了伺服器方面的壓力,現在就這個開發經驗做一個細緻的總結。
目錄
- 原理介紹
- 方法總結
- 實戰演練
原理介紹
這裡先介紹一下檔案上傳的原理,幫助理清這個頭緒。
普通上傳
一般網站上都是普通上傳的比較多,大多數都是上傳一些使用者的頭像,使用者的動態評論附帶圖片什麼的,所以先來說一下這個的原理。
- 使用者選擇檔案後,js檢測檔案大小是否超出限制和格式是否正確;
- 檢查後使用ajax提交請求,服務端也進行二次驗證後儲存到伺服器;
- 後端返回檔案地址到前端,渲染頁面資料;
大檔案上傳
- 使用者選擇檔案後,js檢測檔案大小是否超出限制和格式是否正確;
- 根據檔案大小,使用
file.slice
方法進行檔案分割; - 使用
SparkMD5
和FileReader
API生成檔案唯一的md5值; - 使用ajax提交請求,服務端收到後返回檔案在伺服器的資訊;
- 如果存在這個md5值的資料夾,則返回資料夾裡面上傳了多少檔案;
- 不存在則新建一個這個md5值的資料夾,返回空內容;
- 前端收到資訊後,根據返回資訊作出判斷;
- 如果返回的檔案長度等於切片的總長度,則請求合併檔案;
- 如果返回的檔案長度小於切片的總長度,則開始上傳對應的切片檔案,直至上傳完最後一個切片再請求合併檔案;
- 後端收到合併的請求後,對對應的md5值的資料夾裡面的檔案進行合併,返回檔案地址;
- 前端收到檔案地址後,渲染頁面資料;
斷點續傳
這個的意思就是檔案上傳過程中,如果遇到不可抗力,比如網路中斷,伺服器異常,或者其他原因導致上傳中斷;
下次再次上傳時候,服務端根據這個檔案的md5值找出上傳了多少,還剩下多少未上傳,傳送給客戶端,客戶端收到後繼續對未上傳的進行上傳,上傳完成後合併檔案並返回地址。
這樣就避免了檔案重複上傳,浪費伺服器空間使用,節約伺服器資源,而且速度比上傳一個大檔案更快,更高效。
方法總結
接下來根據上面的邏輯原理分析步驟,進行程式碼功能實現。
普通檔案
本小節講述普通檔案的上傳,包括前端部分和後端部分。
前端部分
- html部分
先來建立個小房子
<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"> 當前進度: <p> <span style="width: 0;" id="current"></span> </p> </div> <div class="upload-link"> 檔案地址:<a id="links" href="javascript:void();" 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"> 當前進度: <p> <span style="width: 0;" id="big-current"></span> </p> </div> <div class="upload-link"> 檔案地址:<a id="big-links" href="" target="_blank">檔案連結</a> </div> </form> </div>
引入axios
和spark-md5
兩個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部分
來裝飾一下這個房子。
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部分
最後加上互動效果。
// 獲取元素
const file = document.querySelector('#file');
let current = document.querySelector('#current');
let links = document.querySelector('#links');
let baseUrl = 'http://localhost:3000';
// 監聽檔案事件
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
,先來下載安裝一個處理檔案的包formidable
,然後開始處理上傳的檔案啦!
新建一個資料夾,別忘了在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.js
const 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;
大檔案
這個大檔案斷點續傳,其實就是在之前檔案上傳的基礎上進一步擴充套件而來的。所以前端部分的結構和樣式一樣,就是方法不一樣。
前端部分
這裡主要是方法介紹。
- 獲取元素
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('檔案格式只能是文件應用!');
}
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);
}
}
後端部分
- 獲取引數
獲取上傳引數並且作判斷。
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: '檔案切片數量不能為空!'
}
})
}
if (!typeArr.includes(type)) {
return res.json({
code: 101,
msg: 'get_fail',
data: {
info: '上傳型別錯誤!'
}
})
}
- 型別是檢測
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: '檔案當前分片值不能為空!'
}
})
}
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
}
})
}
在合併這個功能裡面主要使用的是fs
的createWriteStream
以及createReadStream
方法實現的。
- 合併檔案
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;
}
實戰演練
現在方法也寫好了,來測試下是否OK。
這裡準備了兩個檔案,來分別測試兩個功能。
- 普通檔案
這個是普通檔案上傳介面
上傳成功後:
後端返回內容:
開啟檔案地址預覽:
可以看到成功了!
- 大檔案
這個是大檔案檔案上傳介面
上傳成功後:
這個是某個分片檔案正在上傳:
這個是檔案分片上傳後合併返回的內容:
開啟檔案地址預覽:
再次上傳發現很快返回檔案地址:
這個是nodejs目錄截圖,可以看到檔案的分片儲存完好,合併的也很好。
這個檔案上傳和斷點續傳就講到這裡,當然,我上面所說的方法只是一種,作為參考。如果你有更好的方法,請聯絡我。