UNPKG

file-fragment-upload

Version:

文件分片上传 获取文件hash值 文件分片

66 lines (59 loc) 1.99 kB
import SparkMD5 from 'spark-md5'; /** * 获取文件的hash值,即md5值 * @param file 要分割的文件对象 * @param chunkSize 分片大小,默认每片大小为为3M * @returns */ const getFileHash = (file: File, chunkSize: number = 3 * 1024 * 1024) => { const blobSlice = File.prototype.slice; 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 => { if (e.target && e.target.result) { spark.append(e.target.result as ArrayBuffer); // Append array buffer currentChunk += 1; if (currentChunk < chunks) { loadNext(); } else { 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 = err => { reject(err); }; loadNext(); }).catch(err => { console.error(err); }); }; /** * * @param startByte 分片起始位置 * @param endByte 分片结束位置 * @returns */ const getChunk = (file: File, startByte: number, endByte: number) => { // @ts-ignore const blobSlice = File.prototype.slice || File.prototype.mozSlice || File.prototype.webkitSlice; const chunk = blobSlice.call(file, startByte, endByte); return chunk; }; export { getFileHash, getChunk };