SparkMD5 is a fast md5 implementation of the MD5 algorithm.
文档
CDN引入
<script src="https://cdn.bootcdn.net/ajax/libs/spark-md5/3.0.2/spark-md5.min.js"></script>
npm安装
npm install --save spark-md5
使用方式一:
var hexHash = SparkMD5.hash('Hi there')
console.log(hexHash)
使用方式二:
var spark = new SparkMD5()
spark.append('Hi')
spark.append(' ')
spark.append('there')
var hexHash = spark.end()
console.log(hexHash)
计算文件md5值
<script src="https://cdn.bootcdn.net/ajax/libs/spark-md5/3.0.2/spark-md5.min.js"></script>
<input
type="file"
id="file"
/>
<script>
function getFileMd5(file) {
return new Promise((resolve, reject) => {
let fileReader = new FileReader()
fileReader.onload = function (event) {
let fileMd5 = SparkMD5.ArrayBuffer.hash(event.target.result)
resolve(fileMd5)
}
fileReader.readAsArrayBuffer(file)
})
}
document.getElementById('file').onchange = function (event) {
let file = event.target.files[0]
getFileMd5(file).then((md5) => {
console.log(md5)
})
}
</script>
分片读取文件,并计算md5值
<script src="https://cdn.bootcdn.net/ajax/libs/spark-md5/3.0.2/spark-md5.min.js"></script>
<input
type="file"
id="file"
/>
<script>
function getFileMd5BySlice(file, chunkSize) {
let defaultChunkSize = 1024 * 1024 * 2
return new Promise((resolve, reject) => {
chunkSize = chunkSize || defaultChunkSize
let blobSlice =
File.prototype.slice ||
File.prototype.mozSlice ||
File.prototype.webkitSlice,
chunks = Math.ceil(file.size / chunkSize),
currentChunk = 0,
spark = new SparkMD5.ArrayBuffer(),
fileReader = new FileReader()
fileReader.onload = function (e) {
console.log('read chunk nr', currentChunk + 1, 'of', chunks)
spark.append(e.target.result)
currentChunk++
if (currentChunk < chunks) {
loadNext()
} else {
resolve(spark.end())
}
}
fileReader.onerror = function (error) {
reject(error)
}
function loadNext() {
let start = currentChunk * chunkSize
let end = start + chunkSize
if (end >= file.size) {
end = file.size
}
fileReader.readAsArrayBuffer(blobSlice.call(file, start, end))
}
loadNext()
})
}
document.getElementById('file').addEventListener('change', function (e) {
let startTime = new Date().getTime()
let file = e.target.files[0]
getFileMd5BySlice(file).then((res) => {
console.log(res)
console.log(new Date().getTime() - startTime)
})
})
</script>
参考 spark.md5.js获取文件的md5值
|