導語:之前做過一個小項目,其中用到了文件上傳,在大文件上面使用了斷點續傳,降低了服務器方面的壓力,現在就這個開發經驗做一個細致的總結。
目錄
- 原理介紹
- 方法總結
- 實戰演練
原理介紹
這里先介紹一下文件上傳的原理,幫助理清這個頭緒。
普通上傳
一般網站上都是普通上傳的比較多,大多數都是上傳一些用戶的頭像,用戶的動態評論附帶圖片什么的,所以先來說一下這個的原理。
- 用戶選擇文件后,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目錄截圖,可以看到文件的分片保存完好,合並的也很好。
這個文件上傳和斷點續傳就講到這里,當然,我上面所說的方法只是一種,作為參考。如果你有更好的方法,請聯系我。