You need to enable JavaScript to run this app. 多文件上传预览时如何为不同类型文档匹配对应专属图标
优惠活动
大模型
产品
解决方案
定价
更多

多文件上传预览时如何为不同类型文档匹配对应专属图标

多文件上传按类型匹配专属预览图标改造方案

核心实现逻辑

  • 提前维护文件后缀与对应图标的路径映射表,统一管理不同类型的图标配置
  • 在渲染每个文件预览项时,先提取当前上传文件的真实后缀,匹配映射表中对应的图标路径,匹配失败时回退到原有默认图标
  • 所有图标路径均使用本地项目内的资源路径,无需引用外部第三方服务

改造后完整代码

let file_array = [];
// 自定义文件类型图标映射表,可根据项目实际图标存放路径修改配置
const FILE_TYPE_ICON_MAP = {
  // 图片类
  jpg: '/img/icons/jpg.png',
  jpeg: '/img/icons/jpg.png',
  png: '/img/icons/png.png',
  gif: '/img/icons/gif.png',
  webp: '/img/icons/png.png',
  // 文档类
  pdf: '/img/icons/pdf.png',
  doc: '/img/icons/word.png',
  docx: '/img/icons/word.png',
  xls: '/img/icons/excel.png',
  xlsx: '/img/icons/excel.png',
  ppt: '/img/icons/ppt.png',
  pptx: '/img/icons/ppt.png',
  txt: '/img/icons/txt.png',
  // 压缩包类
  zip: '/img/icons/zip.png',
  rar: '/img/icons/zip.png',
  '7z': '/img/icons/zip.png',
  // 音视频类
  mp4: '/img/icons/video.png',
  mp3: '/img/icons/audio.png',
};
// 未匹配到对应类型时的默认图标
const DEFAULT_FILE_ICON = '/img/fileType.png';

function scrollBottom() {
  let element = document.querySelector('.chat-item-body');
  element.scrollTop = element.scrollHeight - element.clientHeight;
}
scrollBottom();

$("#chat-file").change(function() {
  let input_files = document.getElementById('chat-file').files;
  $.each(input_files, function(index, value) {
    file_array.push(value);
    // 提取文件后缀,统一转小写避免大小写匹配失效
    const fileExt = value.name.split('.').pop().toLowerCase();
    // 匹配对应图标路径,未匹配到则使用默认图标
    const currentIconPath = FILE_TYPE_ICON_MAP[fileExt] || DEFAULT_FILE_ICON;
    
    $('.preview__container').append(`
            <div class="preview__content">
                <div class="img"><img src="${currentIconPath}" alt=""></div>
                <p>${value.name}</p>
                <i class="far fa-times-circle delete_file" data-id="${file_array.length - 1}"></i>
                <p class="delete_file" data-id="${file_array.length - 1}">x</p>
            </div>
            `);
  });
});

$(document.body).on('click', '.delete_file', function() {
  let file_id = $(this).data('id');
  delete file_array[file_id];
  $(this).parent().remove();
});

配置扩展说明

  • 如需新增某类文件的专属图标,只需在FILE_TYPE_ICON_MAP对象中新增对应后缀键值对,填写本地图标路径即可
  • 若需基于文件MIME类型匹配,可将提取后缀的逻辑替换为读取value.type字段,自行调整映射表的键名即可,适配逻辑完全一致
  • 对于无后缀名的文件,会自动命中默认图标展示,不会出现资源加载异常

内容的提问来源于stack exchange,提问作者Tanita Park

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.23 06:54:04