You cannot select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
|
|
|
|
/**
|
|
|
|
|
* 判断文件名是否为图片
|
|
|
|
|
* @param {string} filename 完整文件名(含路径和扩展名)
|
|
|
|
|
* @returns {boolean} 是否为图片
|
|
|
|
|
*/
|
|
|
|
|
|
|
|
|
|
const IMAGE_EXTENSIONS = new Set([
|
|
|
|
|
"jpg",
|
|
|
|
|
"jpeg",
|
|
|
|
|
"png",
|
|
|
|
|
"gif",
|
|
|
|
|
"bmp",
|
|
|
|
|
"svg",
|
|
|
|
|
"webp",
|
|
|
|
|
"tiff",
|
|
|
|
|
"psd",
|
|
|
|
|
"ico",
|
|
|
|
|
"jfif",
|
|
|
|
|
"apng",
|
|
|
|
|
"avif",
|
|
|
|
|
]);
|
|
|
|
|
export function isImage(filename) {
|
|
|
|
|
// 1. 去除路径,只保留文件名
|
|
|
|
|
const baseName = filename.split("/").pop().split("\\").pop();
|
|
|
|
|
if (!baseName) return false;
|
|
|
|
|
|
|
|
|
|
// 2. 提取扩展名(处理多扩展名,取最后一个)
|
|
|
|
|
const ext = baseName.split(".").pop()?.toLowerCase();
|
|
|
|
|
if (!ext || ext.length < 2) return false; // 扩展名长度至少2位(如.jpg)
|
|
|
|
|
|
|
|
|
|
// 3. 检查是否在图片扩展名白名单
|
|
|
|
|
return IMAGE_EXTENSIONS.has(ext);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// 示例测试
|
|
|
|
|
// console.log(isImage('photo.jpg')); // true
|
|
|
|
|
// console.log(isImage('image.png')); // true
|
|
|
|
|
// console.log(isImage('logo.svg')); // true
|
|
|
|
|
// console.log(isImage('cover.tar.gz')); // false(非图片扩展名)
|
|
|
|
|
// console.log(isImage('file')); // false(无扩展名)
|
|
|
|
|
// console.log(isImage('.hidden.png')); // true(隐藏文件)
|
|
|
|
|
// console.log(isImage('icon.JPEG')); // true(大小写不敏感)
|
|
|
|
|
// console.log(isImage('video.mp4')); // false(视频)
|