实现代码
/** * 文件分片 */ function getFileChunks(file, chunkSize) { let chunks = [] // 默认分片大小 2MB let defaultChunkSize = 1024 * 1024 * 2 chunkSize = chunkSize || defaultChunkSize let blobSlice = File.prototype.slice || File.prototype.mozSlice || File.prototype.webkitSlice let current = 0 while (current < file.size) { let chunk = blobSlice.call(file, current, current + chunkSize) chunks.push(chunk) current += chunkSize } return chunks }
<input type="file" id="file" /> <script> document.querySelector('#file').addEventListener('change', function (e) { let file = e.target.files[0] let chunks = getFileChunks(file, 1024 * 1) console.log(chunks) }) </script>
文件切片结果