萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 腳本程式專題 >> JavaScript

jQuery 取得上傳檔案名稱與副檔名:正則表達式完整解析

前言

從 <input type="file"> 的 value 屬性取得純檔名與副檔名,是表單驗證、檔案分類、上傳前檢查的基礎操作。瀏覽器回傳的路徑格式不一 (Windows: C:\fakepath\file.jpg、Mac/Linux: /home/user/file.jpg、或僅檔名),需用健壯的正則或標準 API 處理。

現代標準方案:File API (推薦,無需正則)


const input = document.getElementById('file-input');
input.addEventListener('change', () => {
    const file = input.files[0];
    if (!file) return;

    // 直接取得純檔名 (不含路徑)
    const fileName = file.name; // "我的照片.jpg"
    
    // 取得副檔名 (含點號)
    const ext = fileName.slice(fileName.lastIndexOf('.')); // ".jpg"
    // 或不含點號
    const extNoDot = fileName.split('.').pop().toLowerCase(); // "jpg"
    
    // 取得不含副檔名的純檔名
    const baseName = fileName.slice(0, fileName.lastIndexOf('.')); // "我的照片"
    
    console.log({ fileName, ext, extNoDot, baseName });
});

優點:跨平台一致、無路徑干擾、支援 Unicode 檔名、可同時取得 file.size, file.type, file.lastModified。

傳統 jQuery 方案:解析 input.value (舊專案維護)

input.value 在舊瀏覽器/某些情況下回傳完整偽裝路徑,需正則提取。

方法一:通用路徑分割 (最簡單、最穩健)


$('input[type="file"]').on('change', function() {
    const fullPath = $(this).val(); // "C:\fakepath\image.png" 或 "/home/user/image.png"
    
    // 統一處理反斜線與正斜線
    const fileName = fullPath.replace(/^.*[\\\/]/, ''); // "image.png"
    
    // 取得副檔名
    const ext = fileName.slice(fileName.lastIndexOf('.')).toLowerCase(); // ".png"
    const extNoDot = ext.slice(1); // "png"
    
    // 取得主檔名
    const baseName = fileName.slice(0, fileName.lastIndexOf('.')); // "image"
    
    console.log({ fileName, ext, extNoDot, baseName });
});

正則解析:/^.*[\\\/]/ 匹配從開頭到最後一個斜線 (反斜線或正斜線) 的所有字元,替換為空字串,留下純檔名。

方法二:正則捕獲群組 (單次匹配取得所有部分)


const path = $(this).val();
const match = path.match(/([^\\\/]+)(\.[^.\\\/]+)?$/);

if (match) {
    const fileName = match[0];      // 完整檔名 "image.png"
    const baseName = match[1];      // 主檔名 "image"
    const ext = match[2] || '';     // 副檔名含點 ".png" (若無副檔名為空字串)
}

方法三:嚴格驗證 Windows 路徑字元 (原文方法三改良)


// Windows 禁止檔名字元: \ / : * ? " < > |
// 嚴格匹配合法檔名 (含中文、日文、emoji 等 Unicode)
const strictFileNameRegex = /^([^\\\/:*?"<>|\0]+)(\.[^\\\/:*?"<>|\0]+)?$/;

const fileName = fullPath.replace(/^.*[\\\/]/, '');
if (!strictFileNameRegex.test(fileName)) {
    console.warn('檔名包含非法字元:', fileName);
}

副檔名驗證白名單最佳實踐


const ALLOWED_EXTENSIONS = {
    image: ['jpg', 'jpeg', 'png', 'gif', 'webp', 'bmp', 'svg'],
    document: ['pdf', 'doc', 'docx', 'xls', 'xlsx', 'ppt', 'pptx', 'txt', 'csv'],
    video: ['mp4', 'webm', 'mov', 'avi', 'mkv'],
    audio: ['mp3', 'wav', 'ogg', 'flac', 'aac'],
    archive: ['zip', 'rar', '7z', 'tar', 'gz']
};

function validateFileExtension(fileName, allowedCategories = ['image']) {
    const ext = fileName.slice(fileName.lastIndexOf('.') + 1).toLowerCase();
    const allowed = allowedCategories.flatMap(c => ALLOWED_EXTENSIONS[c] || []);
    
    return {
        isValid: allowed.includes(ext),
        extension: ext,
        allowedExtensions: allowed
    };
}

// 使用
const validation = validateFileExtension(file.name, ['image', 'document']);
if (!validation.isValid) {
    alert(`不支援的檔案格式: .${validation.extension}\n允許格式: ${validation.allowedExtensions.join(', ')}`);
}

完整表單驗證整合範例


class FileUploadValidator {
    constructor(options = {}) {
        this.maxSize = options.maxSize || 10 * 1024 * 1024; // 10MB
        this.allowedCategories = options.allowedCategories || ['image'];
        this.onValid = options.onValid || (() => {});
        this.onInvalid = options.onInvalid || (() => {});
    }

    validate(inputElement) {
        const files = Array.from(inputElement.files);
        const results = files.map(file => this.validateFile(file));
        
        const validFiles = results.filter(r => r.isValid).map(r => r.file);
        const errors = results.filter(r => !r.isValid).map(r => r.error);

        if (errors.length) this.onInvalid(errors, validFiles);
        if (validFiles.length) this.onValid(validFiles, errors);
        
        return { validFiles, errors };
    }

    validateFile(file) {
        // 1. 大小檢查
        if (file.size > this.maxSize) {
            return { isValid: false, file, error: `「${file.name}」超過 ${this.maxSize/1024/1024}MB 限制` };
        }

        // 2. 副檔名檢查
        const ext = file.name.slice(file.name.lastIndexOf('.') + 1).toLowerCase();
        const allowed = this.allowedCategories.flatMap(c => ALLOWED_EXTENSIONS[c] || []);
        if (!allowed.includes(ext)) {
            return { isValid: false, file, error: `「${file.name}」格式不支援 (允許: ${allowed.join(', ')})` };
        }

        // 3. MIME 類型二次檢查 (防止偽裝副檔名)
        const mimeCategory = file.type.split('/')[0]; // image, video, application...
        if (!this.allowedCategories.includes(mimeCategory) && 
            !(mimeCategory === 'application' && allowed.includes(ext))) {
            return { isValid: false, file, error: `「${file.name}」檔案類型與副檔名不符` };
        }

        return { isValid: true, file, extension: ext };
    }
}

// 使用
const validator = new FileUploadValidator({
    maxSize: 5 * 1024 * 1024,
    allowedCategories: ['image', 'document'],
    onValid: (files) => console.log('通過驗證:', files.map(f => f.name)),
    onInvalid: (errors) => errors.forEach(e => console.error(e))
});

$('#file-input').on('change', function() {
    validator.validate(this);
});

特殊情況處理

情況範例處理方式
無副檔名檔案 README, .gitignore lastIndexOf('.') === -1 視為無副檔名,ext = ''
多重副檔名 archive.tar.gz, backup.2024.01.15.zip 通常取最後一段 (.gz, .zip),特殊格式需維護對照表
隱藏檔 (Unix) .bashrc, .env lastIndexOf('.') === 0 視為無副檔名 (整個是檔名)
中文/Unicode 檔名 報表_2024年.xlsx File API 原生支援,正則需加 u flag: /.../u

總結建議

  1. 現代專案:直接使用 file.name (File API),完全避開路徑解析問題
  2. 舊專案維護:用 val().replace(/^.*[\\\/]/, '') 取純檔名,再 slice(lastIndexOf('.')) 取副檔名
  3. 驗證邏輯:雙重檢查 副檔名白名單 + MIME 類型,防止偽裝檔案
  4. 封裝工具類:將驗證邏輯抽離為可複用 Class/函式,統一錯誤處理與回呼
copyright © 萬盛學電腦網 all rights reserved