diff --git a/ecom-dmb-frontend/apps/web-antd/src/utils/oss-upload.ts b/ecom-dmb-frontend/apps/web-antd/src/utils/oss-upload.ts index 82b84713..005cbda9 100644 --- a/ecom-dmb-frontend/apps/web-antd/src/utils/oss-upload.ts +++ b/ecom-dmb-frontend/apps/web-antd/src/utils/oss-upload.ts @@ -24,22 +24,24 @@ export interface UploadOptions { * @returns 返回文件的SHA-256哈希值(十六进制字符串) */ async function calculateFileHash(file: File): Promise { - 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; } /**