UNPKG

t-comm

Version:

专业、稳定、纯粹的工具库

59 lines (55 loc) 1.83 kB
'use strict'; Object.defineProperty(exports, '__esModule', { value: true }); /** * 安全获取文件后缀名 * @param {File} file - 文件对象 * @returns {string} 文件后缀名(小写,不带点) */ function getSafeFileExtension(file) { var _a, _b; // 1. 优先使用type属性获取MIME类型 if (file.type) { var mimeExtension = getExtensionFromMime(file.type); if (mimeExtension) return mimeExtension; } // 2. 使用name属性作为备选 if ((_a = file.name) === null || _a === void 0 ? void 0 : _a.includes('.')) { var nameParts = file.name.split('.'); return ((_b = nameParts.pop()) === null || _b === void 0 ? void 0 : _b.toLowerCase()) || 'jpg'; } // 3. 无法确定后缀名 return 'jpg'; } /** * 从MIME类型获取文件后缀 * @param {string} mimeType - MIME类型 * @returns {string|null} 文件后缀或null */ function getExtensionFromMime(mimeType) { var _a; var mimeMap = { // 常见文档类型 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet': 'xlsx', 'application/vnd.ms-excel': 'xls', 'application/vnd.openxmlformats-officedocument.wordprocessingml.document': 'docx', 'application/msword': 'doc', 'application/pdf': 'pdf', 'text/plain': 'txt', // 图片类型 'image/jpeg': 'jpg', 'image/png': 'png', 'image/gif': 'gif', 'image/svg+xml': 'svg', // 压缩文件 'application/zip': 'zip', 'application/x-rar-compressed': 'rar', 'application/x-7z-compressed': '7z', // 视频文件 'video/mp4': 'mp4', 'video/quicktime': 'mov', 'video/x-msvideo': 'avi' }; return (_a = mimeMap[mimeType.toLowerCase()]) !== null && _a !== void 0 ? _a : null; } exports.getExtensionFromMime = getExtensionFromMime; exports.getSafeFileExtension = getSafeFileExtension;