更新版本至 0.0.37,优化文件上传功能,支持大文件分块上传,改用 SparkMD5 计算 Blob 哈希
This commit is contained in:
@@ -1,4 +1,5 @@
|
||||
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') {
|
||||
@@ -12,57 +13,20 @@ export const hashContent = (str: string | Blob | Buffer): Promise<string> | stri
|
||||
return '';
|
||||
};
|
||||
|
||||
// 直接计算整个 Blob 的 MD5
|
||||
export const hashBlob = (blob: Blob): Promise<string> => {
|
||||
return new Promise((resolve, reject) => {
|
||||
const reader = new FileReader();
|
||||
reader.onload = async () => {
|
||||
try {
|
||||
const content = reader.result;
|
||||
if (typeof content === 'string') {
|
||||
resolve(MD5(content).toString());
|
||||
} else if (content) {
|
||||
const contentString = new TextDecoder().decode(content);
|
||||
resolve(MD5(contentString).toString());
|
||||
} else {
|
||||
reject(new Error('Empty content'));
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('hashBlob error', error);
|
||||
reject(error);
|
||||
}
|
||||
};
|
||||
reader.onerror = (error) => reject(error);
|
||||
reader.readAsArrayBuffer(blob);
|
||||
});
|
||||
};
|
||||
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) => {
|
||||
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);
|
||||
};
|
||||
|
||||
// 读取文件为 ArrayBuffer
|
||||
reader.readAsArrayBuffer(file);
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
export const hashFile = (file: File): Promise<string> => {
|
||||
return hashBlob(file);
|
||||
};
|
||||
|
||||
Reference in New Issue
Block a user