咱們在作文件上傳的時候,若是文件過大,可能會致使請求超時的狀況。因此,在遇到須要對大文件進行上傳的時候,就須要對文件進行分片上傳的操做。同時若是文件過大,在網絡不佳的狀況下,如何作到斷點續傳?也是須要記錄當前上傳文件,而後在下一次進行上傳請求的時候去作判斷。css
先上代碼:代碼倉庫地址html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>文件上傳</title> <script src="https://cdn.bootcss.com/axios/0.18.0/axios.min.js"></script> <script src="https://code.jquery.com/jquery-3.4.1.js"></script> <script src="./spark-md5.min.js"></script> <script> $(document).ready(() => { const chunkSize = 1 * 1024 * 1024; // 每一個chunk的大小,設置爲1兆 // 使用Blob.slice方法來對文件進行分割。 // 同時該方法在不一樣的瀏覽器使用方式不一樣。 const blobSlice = File.prototype.slice || File.prototype.mozSlice || File.prototype.webkitSlice; const hashFile = (file) => { return new Promise((resolve, reject) => { const chunks = Math.ceil(file.size / chunkSize); let currentChunk = 0; const spark = new SparkMD5.ArrayBuffer(); const fileReader = new FileReader(); function loadNext() { const start = currentChunk * chunkSize; const end = start + chunkSize >= file.size ? file.size : start + chunkSize; fileReader.readAsArrayBuffer(blobSlice.call(file, start, end)); } fileReader.onload = e => { spark.append(e.target.result); // Append array buffer currentChunk += 1; if (currentChunk < chunks) { loadNext(); } else { console.log('finished loading'); const result = spark.end(); // 若是單純的使用result 做爲hash值的時候, 若是文件內容相同,而名稱不一樣的時候 // 想保留兩個文件沒法保留。因此把文件名稱加上。 const sparkMd5 = new SparkMD5(); sparkMd5.append(result); sparkMd5.append(file.name); const hexHash = sparkMd5.end(); resolve(hexHash); } }; fileReader.onerror = () => { console.warn('文件讀取失敗!'); }; loadNext(); }).catch(err => { console.log(err); }); } const submitBtn = $('#submitBtn'); submitBtn.on('click', async () => { const fileDom = $('#file')[0]; // 獲取到的files爲一個File對象數組,若是容許多選的時候,文件爲多個 const files = fileDom.files; const file = files[0]; if (!file) { alert('沒有獲取文件'); return; } const blockCount = Math.ceil(file.size / chunkSize); // 分片總數 const axiosPromiseArray = []; // axiosPromise數組 const hash = await hashFile(file); //文件 hash // 獲取文件hash以後,若是須要作斷點續傳,能夠根據hash值去後臺進行校驗。 // 看看是否已經上傳過該文件,而且是否已經傳送完成以及已經上傳的切片。 console.log(hash); for (let i = 0; i < blockCount; i++) { const start = i * chunkSize; const end = Math.min(file.size, start + chunkSize); // 構建表單 const form = new FormData(); form.append('file', blobSlice.call(file, start, end)); form.append('name', file.name); form.append('total', blockCount); form.append('index', i); form.append('size', file.size); form.append('hash', hash); // ajax提交 分片,此時 content-type 爲 multipart/form-data const axiosOptions = { onUploadProgress: e => { // 處理上傳的進度 console.log(blockCount, i, e, file); }, }; // 加入到 Promise 數組中 axiosPromiseArray.push(axios.post('/file/upload', form, axiosOptions)); } // 全部分片上傳後,請求合併分片文件 await axios.all(axiosPromiseArray).then(() => { // 合併chunks const data = { size: file.size, name: file.name, total: blockCount, hash }; axios .post('/file/merge_chunks', data) .then(res => { console.log('上傳成功'); console.log(res.data, file); alert('上傳成功'); }) .catch(err => { console.log(err); }); }); }); }) window.onload = () => { } </script> </head> <body> <h1>大文件上傳測試</h1> <section> <h3>自定義上傳文件</h3> <input id="file" type="file" name="avatar"/> <div> <input id="submitBtn" type="button" value="提交"> </div> </section> </body> </html>
const Koa = require('koa'); const app = new Koa(); const Router = require('koa-router'); const multer = require('koa-multer'); const serve = require('koa-static'); const path = require('path'); const fs = require('fs-extra'); const koaBody = require('koa-body'); const { mkdirsSync } = require('./utils/dir'); const uploadPath = path.join(__dirname, 'uploads'); const uploadTempPath = path.join(uploadPath, 'temp'); const upload = multer({ dest: uploadTempPath }); const router = new Router(); app.use(koaBody()); /** * single(fieldname) * Accept a single file with the name fieldname. The single file will be stored in req.file. */ router.post('/file/upload', upload.single('file'), async (ctx, next) => { console.log('file upload...') // 根據文件hash建立文件夾,把默認上傳的文件移動當前hash文件夾下。方便後續文件合併。 const { name, total, index, size, hash } = ctx.req.body; const chunksPath = path.join(uploadPath, hash, '/'); if(!fs.existsSync(chunksPath)) mkdirsSync(chunksPath); fs.renameSync(ctx.req.file.path, chunksPath + hash + '-' + index); ctx.status = 200; ctx.res.end('Success'); }) router.post('/file/merge_chunks', async (ctx, next) => { const { size, name, total, hash } = ctx.request.body; // 根據hash值,獲取分片文件。 // 建立存儲文件 // 合併 const chunksPath = path.join(uploadPath, hash, '/'); const filePath = path.join(uploadPath, name); // 讀取全部的chunks 文件名存放在數組中 const chunks = fs.readdirSync(chunksPath); // 建立存儲文件 fs.writeFileSync(filePath, ''); if(chunks.length !== total || chunks.length === 0) { ctx.status = 200; ctx.res.end('切片文件數量不符合'); return; } for (let i = 0; i < total; i++) { // 追加寫入到文件中 fs.appendFileSync(filePath, fs.readFileSync(chunksPath + hash + '-' +i)); // 刪除本次使用的chunk fs.unlinkSync(chunksPath + hash + '-' +i); } fs.rmdirSync(chunksPath); // 文件合併成功,能夠把文件信息進行入庫。 ctx.status = 200; ctx.res.end('合併成功'); }) app.use(router.routes()); app.use(router.allowedMethods()); app.use(serve(__dirname + '/static')); app.listen(9000);
const path = require('path'); const fs = require('fs-extra'); const mkdirsSync = (dirname) => { if(fs.existsSync(dirname)) { return true; } else { if (mkdirsSync(path.dirname(dirname))) { fs.mkdirSync(dirname); return true; } } } module.exports = { mkdirsSync };
咱們如下的操做都是保證在已經安裝node以及npm的前提下進行。node的安裝以及使用能夠參考 官方網站。
安裝相關依賴node
npm i koa npm i koa-router --save // Koa路由 npm i koa-multer --save // 文件上傳處理模塊 npm i koa-static --save // Koa靜態資源處理模塊 npm i fs-extra --save // 文件處理 npm i koa-body --save // 請求參數解析
建立項目結構jquery
file-upload - static - index.html - spark-md5.min.js - uploads - temp - utils - dir.js - app.js
其中細節部分代碼裏有相應的註釋說明,瀏覽代碼就一目瞭然。 後續延伸:斷點續傳、多文件多批次上傳