js html5 获取文件md5,How to calculate md5 hash of a file using javascript

这段代码展示了如何通过WebAssembly库hash-wasm实现读取大文件并进行哈希计算,达到400MB/s的高吞吐量。它利用WebAssembly的性能优势,比纯JavaScript库更快地计算MD5哈希值。适用于现代浏览器。
摘要由CSDN通过智能技术生成

The following snippet shows an example, which can archive a throughput of 400 MB/s while reading and hashing the file.

It is using a library called hash-wasm, which is based on WebAssembly and calculates the hash faster than js-only libraries. As of 2020, all modern browsers support WebAssembly.

const chunkSize = 64 * 1024 * 1024;

const fileReader = new FileReader();

let hasher = null;

function hashChunk(chunk) {

return new Promise((resolve, reject) => {

fileReader.onload = async(e) => {

const view = new Uint8Array(e.target.result);

hasher.update(view);

resolve();

};

fileReader.readAsArrayBuffer(chunk);

});

}

const readFile = async(file) => {

if (hasher) {

hasher.init();

} else {

hasher = await hashwasm.createMD5();

}

const chunkNumber = Math.floor(file.size / chunkSize);

for (let i = 0; i <= chunkNumber; i++) {

const chunk = file.slice(

chunkSize * i,

Math.min(chunkSize * (i + 1), file.size)

);

await hashChunk(chunk);

}

const hash = hasher.digest();

return Promise.resolve(hash);

};

const fileSelector = document.getElementById("file-input");

const resultElement = document.getElementById("result");

fileSelector.addEventListener("change", async(event) => {

const file = event.target.files[0];

resultElement.innerHTML = "Loading...";

const start = Date.now();

const hash = await readFile(file);

const end = Date.now();

const duration = end - start;

const fileSizeMB = file.size / 1024 / 1024;

const throughput = fileSizeMB / (duration / 1000);

resultElement.innerHTML = `

Hash: ${hash}

Duration: ${duration} ms

Throughput: ${throughput.toFixed(2)} MB/s

`;

});

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值