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哈希值(十六进制字符串) * @returns 返回文件的SHA-256哈希值(十六进制字符串)
*/ */
async function calculateFileHash(file: File): Promise<string> { async function calculateFileHash(file: File): Promise<string> {
const arrayBuffer = await file.arrayBuffer(); // 尝试使用标准 Web Crypto API
// 兼容不同环境的 crypto.subtle if (typeof crypto !== 'undefined' && crypto.subtle) {
const cryptoSubtle = typeof crypto !== 'undefined' && crypto.subtle try {
? crypto.subtle const arrayBuffer = await file.arrayBuffer();
: (window as any).crypto?.subtle; const hashBuffer = await crypto.subtle.digest('SHA-256', arrayBuffer);
const hashArray = [...new Uint8Array(hashBuffer)];
if (!cryptoSubtle) { return hashArray
throw new Error('当前环境不支持文件加密计算,请使用现代浏览器'); .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 const pseudoHash = `${file.name}_${file.size}_${file.lastModified}`;
.map((b) => b.toString(16).padStart(2, '0')) return pseudoHash;
.join('');
return hashHex;
} }
/** /**