如何使用jQuery显示自定义样式输入文件的文件名?

47

我使用 CSS 样式表对文件输入框进行了样式设置:

.custom-file-upload {
  border: 1px solid #ccc;
  display: inline-block;
  padding: 6px 12px;
  cursor: pointer; 
}
<form>
  <label for="file-upload" class="custom-file-upload">
    <i class="fa fa-cloud-upload"></i> Upload Image
  </label>
  <input id="file-upload" name='upload_cont_img' type="file" style="display:none;">
</form>  

一切都运行良好,但我想显示所选文件的名称。如何使用CSS或jQuery实现这一点?


1
可能是Styling an input type="file" button的重复问题。 - Advaith
如果您可以将名称属性放在标签中,则可以使用attr()函数(无法向输入元素添加生成的内容)仅使用CSS完成此操作。http://codepen.io/danield770/pen/XpmNYZ?editors=1100#0 - Danield
7个回答

59

您需要绑定并触发[type=file]元素上的更改事件,并将文件名读取为:

$('#file-upload').change(function() {
  var i = $(this).prev('label').clone();
  var file = $('#file-upload')[0].files[0].name;
  $(this).prev('label').text(file);
});
.custom-file-upload {
  border: 1px solid #ccc;
  display: inline-block;
  padding: 6px 12px;
  cursor: pointer;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
  <label for="file-upload" class="custom-file-upload">
    <i class="fa fa-cloud-upload"></i> Upload Image
  </label>
  <input id="file-upload" name='upload_cont_img' type="file" style="display:none;">
</form>


@ Jai 这正是我想要的。非常感谢。 - amM
对我来说,+1,但是使用$('#file-upload')[0].files[0].name;对我没有用,但是使用$('#file-upload').files[0].name;可以正常工作。 - IamCavic
如果您的标签在输入框之后,则$(this).next('label').text(file); - Chris

31

当输入变化时,您需要获取文件名并将其插入到HTML中。在代码中,this.files [0] .name 获取所选文件的名称。

$("#file-upload").change(function(){
  $("#file-name").text(this.files[0].name);
});

$("#file-upload").change(function(){
  $("#file-name").text(this.files[0].name);
});
.custom-file-upload {
    border: 1px solid #ccc;
    display: inline-block;
    padding: 6px 12px;
    cursor: pointer; 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
    <label for="file-upload" class="custom-file-upload">
        <i class="fa fa-cloud-upload"></i> Upload Image
    </label>
    <input id="file-upload" name='upload_cont_img' type="file" style="display:none;">
    <label id="file-name"></label>
</form>

你也可以使用纯JavaScript来完成这项工作。

document.querySelector("#file-upload").onchange = function(){
  document.querySelector("#file-name").textContent = this.files[0].name;
}

document.querySelector("#file-upload").onchange = function(){
  document.querySelector("#file-name").textContent = this.files[0].name;
}
.custom-file-upload {
  border: 1px solid #ccc;
  display: inline-block;
  padding: 6px 12px;
  cursor: pointer; 
}
<form>
  <label for="file-upload" class="custom-file-upload">
    <i class="fa fa-cloud-upload"></i> Upload Image
  </label>
  <input id="file-upload" name='upload_cont_img' type="file" style="display:none;">
  <label id="file-name"></label>
</form>


13

你也可以将其用于多文件上传

updateList = function() {
  var input = document.getElementById('file');
  var output = document.getElementById('fileList');

  output.innerHTML = '<ul>';
  for (var i = 0; i < input.files.length; ++i) {
    output.innerHTML += '<li>' + input.files.item(i).name + '</li>';
  }
  output.innerHTML += '</ul>';
}
<input type="file" name="file" id="file" multiple 
       onchange="javascript:updateList()" />
<br/>Selected files:
<div id="fileList"></div>


简单、高效、可定制。感谢您提供如此简单而强大的代码片段。 这个对我来说很有用。(L) - Samuel Ramzan

8
您可以像这样获取文件名
$('#file-upload')[0].files[0].name

这是正确的,但不完美。它只获取文件名,当输入更改时应使用它,并将获取的名称设置在HTML中。 - Mohammad

4

由于浏览器持续更新,CSS修复在所有浏览器上都不是有效的解决方案,请使用JavaScript版本来解决上述问题。

解决方法1

CSS片段

.wrap-file_upload{position:relative; display:inline-block;}
.wrap-file_upload .btn_colorlayer,.wrap-file_upload:hover .btn_colorlayer{position: absolute; left: 102%; padding-left: 8px; max-width: 120px; white-space: nowrap;text-overflow: ellipsis; overflow: hidden; color:#d7263d;top: 50%; margin-top: -8px; text-transform: none; pointer-events:none; }
.wrap-file_upload input[type="file"]{opacity: 0; height:40px; display: inline; position: absolute; left: 0; top: 0; width: 230px; bottom: 0;}
.wrap-file_upload .btn_lbl{pointer-events: none;}

JavaScript片段

function _updatename(obj){
    var _parentObj = $(obj).parents("[data-uploadfield]");
    _parentObj.addClass("wrap-file_upload");
    if(!_parentObj.find(".btn_colorlayer").length){
        _parentObj.append("<span class='btn_colorlayer'></span>")
    }
    var _tempname = "";
    if( $(obj).val() != "" && typeof( $(obj).val())!='undefined'){
        _tempname =  $(obj).val().split('\\');
        _tempname = _tempname[_tempname.length-1];
    }

    var _name = _tempname ||  $(obj).parents("[data-uploadfield]").attr("data-uploadfield") || "No file chosen";
    _parentObj.find(".btn_colorlayer").attr("title",_name).text(_name);
}

if($("[data-uploadfield]").length){
    $("[data-uploadfield]").each(function(i){
        _updatename($(this).find("input[type='file']"));
    });
}

$(document).on("click","[data-uploadfield] input[type='file']",function(){
    _updatename($(this));
});

$(document).on("change","[data-uploadfield] input[type='file']",function(){
    _updatename($(this));
});

//  Enable Custom Control for Ajax called pages
$( document ).ajaxComplete(function(event,request,settings){
    if($("[data-uploadfield]").length){
        _updatename("[data-uploadfield] input[type='file']");
    }
});

解决方案2

CSS Only 方案

.file_upload {
  position: relative;
  min-width: 90px;
  text-align: center;
  color: #ee3333;
  line-height: 25px;
  background: #fff;
  border: solid 2px #ee3333;
  font-weight: 600;
}

a.file_upload {
  display: inline-block;
}

.file_upload .btn_lbl {
  position: relative;
  z-index: 2;
  pointer-events: none;
}

.file_upload .btn_colorlayer {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: #fff;
  z-index: 1;
  pointer-events: none;
}

.file_upload input[type="file"] {
  position: absolute;
  top: 3px;
  left: -86px;
  font-weight: 600;
  margin-left: 100%;
  color: #ee3333;
  outline: none;
}
<button class="file_upload" type="button">
      <span class="btn_lbl">Browse</span>
      <span class="btn_colorlayer"></span>
      <input type="file" name="fileupload" id="file_upload" />
    </button>


嗨,我已经删除了你网站的演示链接,因为它可能被视为垃圾邮件。如果链接页面被删除,你的演示可能会失效。因此,我创建了一个可用的片段。 - adiga
1
在Linux上,Firefox中看起来完全崩溃了。 - ceving
如果您使用捷克语,文本会更长,而且在Chrome中也会出现问题。 - Martin Zvarík

3

我有一个很长的裂缝,希望能帮到你。你可能需要更多地进行样式设计以符合你的喜好。

HTML

<form>
  <label for="file-upload" class="custom-file-upload">
    <i class="fa fa-cloud-upload"></i> Upload Image
  </label>
  <input id="file-upload" name='upload_cont_img' type="file"     style="display:none;">
  <input id="uploadFile" placeholder="No File" disabled="disabled" />
</form>

CSS

.custom-file-upload {
  border: 1px solid #ccc;
  display: inline-block;
  padding: 6px 12px;
  cursor: pointer;
}

#uploadFile {
  text-align: center;
  border: none;
  background-color: white;
  color: black;
}

JavaScript

document.getElementById("file-upload").onchange = function() {
  document.getElementById("uploadFile").value = this.value;
};

JSFiddle link:https://jsfiddle.net/kd1brhny/


0

上传按钮样式

input[type="file"] {
    display: none;
}
.custom-file-upload {
    border: 1px solid #ccc;
    display: inline-block;
    padding: 6px 12px;
    cursor: pointer;
}
<label for="file-upload" class="custom-file-upload">
    <i class="fa fa-cloud-upload"></i> Custom Upload
</label>
<input id="file-upload" type="file"/>


优秀的解决方案! - Samuel Ramzan
4
这并没有显示文件名,因此无法回答这个问题。 - KittMedia

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接