写一个ts worker 大文件分片计算sha256,md5,sha1,sha512值
时间: 2024-01-11 16:02:10 浏览: 313
MD5,SHA1,等HASH值计算
好的,我可以为您提供一个 TypeScript 的代码示例,使用 Web Workers 来实现大文件分片计算 SHA256、MD5、SHA1 和 SHA512 哈希值:
```typescript
// 定义一个工作线程的类型,包含计算函数和计算类型
type WorkerType = {
compute: (data: ArrayBuffer) => Promise<string>;
type: string;
};
// 定义一个函数,将文件分成多个 ArrayBuffer
function splitFile(file: File, chunkSize: number): Promise<ArrayBuffer[]> {
return new Promise((resolve, reject) => {
const fileSize = file.size;
const chunks = [];
let offset = 0;
const reader = new FileReader();
function readSlice() {
if (offset >= fileSize) {
resolve(chunks);
return;
}
const slice = file.slice(offset, offset + chunkSize);
reader.readAsArrayBuffer(slice);
offset += chunkSize;
}
reader.addEventListener("load", () => {
chunks.push(reader.result);
readSlice();
});
reader.addEventListener("error", () => {
reject(reader.error);
});
readSlice();
});
}
// 定义一个函数,创建一个工作线程,用于计算哈希值
function createWorker(worker: WorkerType): Worker {
const workerURL = URL.createObjectURL(
new Blob([`(${worker.compute})()`], { type: "application/javascript" })
);
const hashWorker = new Worker(workerURL);
return hashWorker;
}
// 定义一个函数,使用 Web Workers 并行计算文件的哈希值
function computeHashes(file: File): Promise<{ [key: string]: string }> {
const chunkSize = 1024 * 1024; // 分片大小为 1MB
const workers = [
{ compute: sha256, type: "SHA-256" },
{ compute: md5, type: "MD5" },
{ compute: sha1, type: "SHA-1" },
{ compute: sha512, type: "SHA-512" },
];
const promises = workers.map((worker) => {
const hashWorker = createWorker(worker);
const chunksPromise = splitFile(file, chunkSize);
return chunksPromise.then((chunks) => {
const hashPromises = chunks.map((chunk) => {
return new Promise<string>((resolve) => {
const message = { data: chunk };
const onMessage = (event: MessageEvent) => {
hashWorker.removeEventListener("message", onMessage);
resolve(event.data);
};
hashWorker.addEventListener("message", onMessage);
hashWorker.postMessage(message, [message.data]);
});
});
return Promise.all(hashPromises).then((hashes) => ({
[worker.type]: hashes.join(""),
}));
});
});
return Promise.all(promises).then((results) => {
const hashes = Object.assign({}, ...results);
return hashes;
});
}
// SHA-256 计算函数
function sha256(): void {
self.addEventListener("message", async (event: MessageEvent) => {
const data = event.data as ArrayBuffer;
const hashBuffer = await crypto.subtle.digest("SHA-256", data);
const hashArray = Array.from(new Uint8Array(hashBuffer));
const hashHex = hashArray.map((b) => b.toString(16).padStart(2, "0")).join("");
self.postMessage(hashHex);
});
}
// MD5 计算函数
function md5(): void {
self.addEventListener("message", async (event: MessageEvent) => {
const data = event.data as ArrayBuffer;
const hashBuffer = await crypto.subtle.digest("MD5", data);
const hashArray = Array.from(new Uint8Array(hashBuffer));
const hashHex = hashArray.map((b) => b.toString(16).padStart(2, "0")).join("");
self.postMessage(hashHex);
});
}
// SHA-1 计算函数
function sha1(): void {
self.addEventListener("message", async (event: MessageEvent) => {
const data = event.data as ArrayBuffer;
const hashBuffer = await crypto.subtle.digest("SHA-1", data);
const hashArray = Array.from(new Uint8Array(hashBuffer));
const hashHex = hashArray.map((b) => b.toString(16).padStart(2, "0")).join("");
self.postMessage(hashHex);
});
}
// SHA-512 计算函数
function sha512(): void {
self.addEventListener("message", async (event: MessageEvent) => {
const data = event.data as ArrayBuffer;
const hashBuffer = await crypto.subtle.digest("SHA-512", data);
const hashArray = Array.from(new Uint8Array(hashBuffer));
const hashHex = hashArray.map((b) => b.toString(16).padStart(2, "0")).join("");
self.postMessage(hashHex);
});
}
```
使用方法:
```typescript
const fileInput = document.getElementById("file-input") as HTMLInputElement;
fileInput.addEventListener("change", async () => {
const file = fileInput.files[0];
const hashes = await computeHashes(file);
console.log(hashes);
});
```
该示例使用 Web Workers 并行计算文件的 SHA256、MD5、SHA1 和 SHA512 哈希值。它将文件分成多个 ArrayBuffer,然后使用指定的算法计算每个 ArrayBuffer 的哈希值。最后,它将所有哈希值组合成一个包含 SHA256、MD5、SHA1 和 SHA512 哈希值的对象。
阅读全文