33 lines
931 B
TypeScript
33 lines
931 B
TypeScript
import MD5 from 'crypto-js/md5';
|
|
import SparkMD5 from 'spark-md5';
|
|
|
|
export const hashContent = (str: string | Blob | Buffer): Promise<string> | string => {
|
|
if (typeof str === 'string') {
|
|
return MD5(str).toString();
|
|
} else if (str instanceof Blob) {
|
|
return hashBlob(str);
|
|
} else if (Buffer.isBuffer(str)) {
|
|
return MD5(str.toString()).toString();
|
|
}
|
|
console.error('hashContent error: input must be a string, Blob, or Buffer');
|
|
return '';
|
|
};
|
|
|
|
// 直接计算整个 Blob 的 MD5
|
|
export const hashBlob = (blob: Blob): Promise<string> => {
|
|
return new Promise(async (resolve, reject) => {
|
|
try {
|
|
const spark = new SparkMD5.ArrayBuffer();
|
|
spark.append(await blob.arrayBuffer());
|
|
resolve(spark.end());
|
|
} catch (error) {
|
|
console.error('hashBlob error', error);
|
|
reject(error);
|
|
}
|
|
});
|
|
};
|
|
|
|
export const hashFile = (file: File): Promise<string> => {
|
|
return hashBlob(file);
|
|
};
|