43 lines
1.2 KiB
TypeScript
43 lines
1.2 KiB
TypeScript
import MD5 from 'crypto-js/md5';
|
|
|
|
export const hashContent = (str: string | Buffer): string => {
|
|
if (typeof str === 'string') {
|
|
return MD5(str).toString();
|
|
} else if (Buffer.isBuffer(str)) {
|
|
return MD5(str.toString()).toString();
|
|
}
|
|
console.error('hashContent error: input must be a string or Buffer');
|
|
return '';
|
|
};
|
|
export const hashFile = (file: File): Promise<string> => {
|
|
return new Promise((resolve, reject) => {
|
|
const reader = new FileReader();
|
|
|
|
reader.onload = async (event) => {
|
|
try {
|
|
const content = event.target?.result;
|
|
if (content instanceof ArrayBuffer) {
|
|
const contentString = new TextDecoder().decode(content);
|
|
const hashHex = MD5(contentString).toString();
|
|
resolve(hashHex);
|
|
} else if (typeof content === 'string') {
|
|
const hashHex = MD5(content).toString();
|
|
resolve(hashHex);
|
|
} else {
|
|
throw new Error('Invalid content type');
|
|
}
|
|
} catch (error) {
|
|
console.error('hashFile error', error);
|
|
reject(error);
|
|
}
|
|
};
|
|
|
|
reader.onerror = (error) => {
|
|
reject(error);
|
|
};
|
|
|
|
// 读取文件为 ArrayBuffer
|
|
reader.readAsArrayBuffer(file);
|
|
});
|
|
};
|