fix: 修复文件上传hash计算失败时使用伪哈希作为备选方案

This commit is contained in:
小蟑螂
2026-03-27 22:16:18 +08:00
parent 12074def77
commit d00547341e
@@ -24,22 +24,24 @@ export interface UploadOptions {
* @returns 返回文件的SHA-256哈希值(十六进制字符串)
*/
async function calculateFileHash(file: File): Promise<string> {
const arrayBuffer = await file.arrayBuffer();
// 兼容不同环境的 crypto.subtle
const cryptoSubtle = typeof crypto !== 'undefined' && crypto.subtle
? crypto.subtle
: (window as any).crypto?.subtle;
if (!cryptoSubtle) {
throw new Error('当前环境不支持文件加密计算,请使用现代浏览器');
// 尝试使用标准 Web Crypto API
if (typeof crypto !== 'undefined' && crypto.subtle) {
try {
const arrayBuffer = await file.arrayBuffer();
const hashBuffer = await crypto.subtle.digest('SHA-256', arrayBuffer);
const hashArray = [...new Uint8Array(hashBuffer)];
return hashArray
.map((b) => b.toString(16).padStart(2, '0'))
.join('');
} catch {
// Fall through to fallback
}
}
const hashBuffer = await cryptoSubtle.digest('SHA-256', arrayBuffer);
const hashArray = [...new Uint8Array(hashBuffer)];
const hashHex = hashArray
.map((b) => b.toString(16).padStart(2, '0'))
.join('');
return hashHex;
// 备选方案:使用文件名+大小+最后修改时间作为伪哈希
// 这种方式不能用于文件去重,但可以保证同一文件每次生成相同的标识
const pseudoHash = `${file.name}_${file.size}_${file.lastModified}`;
return pseudoHash;
}
/**