我們在做文件上傳的時候,如果文件過大,可能會導致請求超時的情況。所以,在遇到需要對大文件進行上傳的時候,就需要對文件進行分片上傳的操作。同時如果文件過大,在網絡不佳的情況下,如何做到斷點續傳?也是需要記錄當前上傳文件,然后在下一次進行上傳請求的時候去做判斷。
先上代碼:代碼倉庫地址
前端
1. index.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>
新聞熱點
疑難解答
圖片精選