You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Spring Boot-Thymeleaf中如何展示PDF、XML、XLSX等非图片上传文件?

解决方案:按文件类型显示对应图标

方案一:用Thymeleaf后端判断(无需JS)

这种方式不用写JS,直接在模板里处理,适合快速实现:

  1. 先准备一套文件图标,放在项目的/static/icons/目录下,比如pdf.png、doc.png、xls.png、default.png(用于没有对应图标的文件)。
  2. 修改你的Thymeleaf代码,通过条件判断区分图片和非图片文件:
<div th:each="tempFile:${files}" class="col-2 mb-4">
    <a th:href="@{'/user/file/' + ${tempFile.idFile}}">
        <!-- 图片文件显示原图片 -->
        <img th:if="${#strings.containsAny(tempFile.fileName.toLowerCase(), '.jpg', '.jpeg', '.png', '.gif', '.webp')}" 
             th:src="@{'/files/'+${tempFile.fileName}}" 
             alt="图片预览">
        <!-- 非图片文件显示对应图标,无对应图标时显示默认图 -->
        <img th:unless="${#strings.containsAny(tempFile.fileName.toLowerCase(), '.jpg', '.jpeg', '.png', '.gif', '.webp')}" 
             th:src="@{'/icons/' + ${#strings.substringAfter(tempFile.fileName.toLowerCase(), '.')} + '.png'}" 
             th:alt="${tempFile.fileName}"
             onerror="this.src='/icons/default.png'">
    </a>
</div>
  • 用toLowerCase()统一处理文件名大小写,避免.JPG、.Pdf这类格式判断失效。
  • onerror属性用于当对应扩展名的图标不存在时,自动切换到默认图标。

方案二:用JavaScript前端动态处理

如果你想用JS实现,步骤如下:

  1. 同样先准备好图标文件放在/static/icons/目录下。
  2. 调整Thymeleaf代码,给图片元素加上自定义属性存储文件名:
<div th:each="tempFile:${files}" class="col-2 mb-4">
    <a th:href="@{'/user/file/' + ${tempFile.idFile}}">
        <img class="file-preview" 
             th:data-filename="${tempFile.fileName}"
             th:src="@{'/files/'+${tempFile.fileName}}" 
             alt="文件预览">
    </a>
</div>
  1. 写一段简单的JS代码,在页面加载完成后处理所有文件预览元素:
// 页面加载完成后执行逻辑
document.addEventListener('DOMContentLoaded', function() {
    // 定义属于图片的扩展名
    const imageTypes = ['jpg', 'jpeg', 'png', 'gif', 'webp'];
    // 处理特殊扩展名映射(比如docx用doc的图标)
    const extMap = {
        'docx': 'doc',
        'xlsx': 'xls',
        'pptx': 'ppt'
    };

    // 获取所有文件预览图片
    const fileElements = document.querySelectorAll('.file-preview');
    
    fileElements.forEach(img => {
        const fileName = img.dataset.filename;
        // 提取文件扩展名并转小写
        const fileExt = fileName.split('.').pop().toLowerCase();
        // 映射特殊扩展名
        const targetExt = extMap[fileExt] || fileExt;

        // 如果不是图片类型,替换为对应图标
        if (!imageTypes.includes(fileExt)) {
            img.src = `/icons/${targetExt}.png`;
            // 图标加载失败时显示默认图
            img.onerror = function() {
                this.src = '/icons/default.png';
            };
        }
    });
});

补充说明

  • 图标文件名要和扩展名对应,比如pdf.png对应所有.pdf文件。
  • 如果需要支持更多文件类型,只需要添加对应的图标文件,并在判断逻辑里补充扩展名即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.10 23:10:12