SparkMD5 is a fast md5 implementation of the MD5 algorithm.
文档
- https://github.com/satazor/js-spark-md5
- https://www.npmjs.com/package/spark-md5
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)
// d9385462d3deff78c352ebb3f941ce12
使用方式二:
var spark = new SparkMD5()
spark.append('Hi')
spark.append(' ')
spark.append('there')
var hexHash = spark.end()
console.log(hexHash)
// d9385462d3deff78c352ebb3f941ce12
计算文件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>
/**
* 计算文件md5值
*/
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)
// e311a516191b1643e3f63cb05163d11a
})
}
</script>
分片读取文件,并计算md5值文章来源:https://www.toymoban.com/news/detail-459572.html
<script src="https://cdn.bootcdn.net/ajax/libs/spark-md5/3.0.2/spark-md5.min.js"></script>
<input
type="file"
id="file"
/>
<script>
/**
* 分片读取文件,计算最终md5值
*/
function getFileMd5BySlice(file, chunkSize) {
// 默认分片大小 2MB
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) // Append array buffer
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)
// 52fde8264e2640cd5b95fdb123de0eba
console.log(new Date().getTime() - startTime)
// 4611 2M
// 4167 10M
// 4333 20M
// 4070 50M
// 4160 100M
})
})
</script>
参考
spark.md5.js获取文件的md5值文章来源地址https://www.toymoban.com/news/detail-459572.html
到了这里,关于js:spark-md5分片计算文件的md5值的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!