t-comm
Version:
专业、稳定、纯粹的工具库
69 lines (67 loc) • 2.19 kB
JavaScript
/**
* 安全获取文件后缀名
* @param {File} file - 文件对象
* @returns {string} 文件后缀名(小写,不带点)
* @example
* ```ts
* const f = new File([''], 'photo.PNG', { type: 'image/png' });
* getSafeFileExtension(f); // 'png'
*
* // 没有 type 时会退化到用文件名后缀
* const f2 = new File([''], 'doc.PDF');
* getSafeFileExtension(f2); // 'pdf'
* ```
*/
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
* @example
* ```ts
* getExtensionFromMime('image/png'); // 'png'
* getExtensionFromMime('application/pdf'); // 'pdf'
* getExtensionFromMime('application/foo-unknown'); // 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;
}
export { getExtensionFromMime, getSafeFileExtension };