Files

32 lines
896 B
TypeScript

import SparkMD5 from 'spark-md5';
export const hashContent = (str: string | Blob | Buffer): Promise<string> | string => {
if (typeof str === 'string') {
return SparkMD5.hash(str);
} else if (str instanceof Blob) {
return hashBlob(str);
} else if (Buffer.isBuffer(str)) {
return SparkMD5.hash(str.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);
};