Last active
August 6, 2022 16:30
-
-
Save semlinker/d99ad82af86680db00734d54e8846ffe to your computer and use it in GitHub Desktop.
Concurrent Upload of Large Files in JavaScript
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function calcFileMD5(file) { | |
return new Promise((resolve, reject) => { | |
let chunkSize = 2097152, // 2M | |
chunks = Math.ceil(file.size / chunkSize), | |
currentChunk = 0, | |
spark = new SparkMD5.ArrayBuffer(), | |
fileReader = new FileReader(); | |
fileReader.onload = (e) => { | |
spark.append(e.target.result); | |
currentChunk++; | |
if (currentChunk < chunks) { | |
loadNext(); | |
} else { | |
resolve(spark.end()); | |
} | |
}; | |
fileReader.onerror = (e) => { | |
reject(fileReader.error); | |
reader.abort(); | |
}; | |
function loadNext() { | |
let start = currentChunk * chunkSize, | |
end = start + chunkSize >= file.size ? file.size : start + chunkSize; | |
fileReader.readAsArrayBuffer(file.slice(start, end)); | |
} | |
loadNext(); | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment