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

如何在Bootstrap中自定义type为file的input上传按钮样式

Bootstrap 自定义文件上传按钮解决方案

核心原理

原生<input type="file">的内置文本由浏览器自带,无法直接通过CSS修改,因此采用「隐藏原生输入框+关联label承载样式」的方案实现自定义按钮,完全保留原有文件选择、表单提交、校验等功能。

基础实现(仅显示Upload文本)

直接替换原有代码为如下内容即可:

<label> Upload File : </label>
<!-- 隐藏原生文件输入框,Bootstrap 4+ 可用自带工具类d-none实现隐藏,低版本可自定义类设置display: none -->
<input type="file" class="d-none form-control required" id="file" name="file" ng-model="Form.file" required>
<!-- label通过for属性绑定输入框id,点击即可触发文件选择,直接添加Bootstrap按钮类即可 -->
<label for="file" class="btn btn-success">
  Upload
</label>

可选扩展:显示选中的文件名

如果需要同时展示用户选中的文件名称,可额外添加文本标签配合简单JS实现:

<label> Upload File : </label>
<input type="file" class="d-none form-control required" id="file" name="file" ng-model="Form.file" required>
<label for="file" class="btn btn-success">
  Upload
</label>
<span id="selectedFileName" class="ms-2 text-muted"></span>
// 监听文件选择事件,更新展示的文件名
document.querySelector('#file').addEventListener('change', function(e) {
  const name = e.target.files[0]?.name || '未选择文件'
  document.querySelector('#selectedFileName').textContent = name
})

该方案无需引入额外依赖,原有Angular双向绑定、required校验等功能均不受影响。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 12:09:01