Как отобразить имя файла для входного файла с пользовательским стилем с помощью jquery?

Я стилизовал ввод файла с помощью 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?


person bdb    schedule 09.01.2017    source источник
comment
Возможный дубликат Стили ввода type=file button   -  person Advaith    schedule 09.01.2017
comment
Если бы вы могли поместить атрибут name в метку, то это можно было бы сделать только с помощью CSS с помощью функции attr() (сгенерированный контент не может быть добавлен к элементам ввода). codepen.io/danield770/pen/XpmNYZ?editors=1100#0   -  person Danield    schedule 09.01.2017


Ответы (7)


Вы должны связать и вызвать событие изменения в элементе [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>

person Jai    schedule 09.01.2017
comment
@ Джай Это именно то, что я хотел. Большое спасибо. - person bdb; 09.01.2017
comment
+1 однако у меня это не сработало с $('#file-upload')[0].files[0].name; но он отлично работал с $('#file-upload').files[0].name; - person IamCavic; 23.02.2018
comment
Если ваша метка находится после ввода, тогда $(this).next('label').text(file); - person Chris; 17.03.2021

Вам нужно получить имя файла при изменении ввода и вставить его в 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>

person Mohammad    schedule 09.01.2017

Вы также можете использовать это для загрузки нескольких файлов

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>

person Gokul P P    schedule 09.01.2017
comment
Простой, эффективный и настраиваемый. Спасибо за такой простой, но мощный фрагмент. Этот сделал это за меня. (л) - person Samuel Ramzan; 06.03.2021

Вы можете взять такое имя файла

$('#file-upload')[0].files[0].name
person Sharmila    schedule 09.01.2017
comment
Правильно покупка не идеальна. Он получает только имя файла, и вы должны использовать его при изменении ввода и установке полученного имени в htm. - person Mohammad; 09.01.2017

Поскольку постоянное обновление исправления 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

.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>

person Growyour GK    schedule 27.11.2018
comment
Привет, я удалил демо-ссылку на ваш сайт, так как это может быть расценено как спам. Ваша демонстрация может стать недействительной, если связанная страница будет удалена. Итак, я создал рабочий фрагмент. - person adiga; 27.11.2018
comment
Выглядит полностью сломанным в FF на Linux. - person ceving; 16.01.2020
comment
он не работает и в Chrome, если вы используете чешский язык, который длиннее в тексте - person Martin Zvarík; 12.03.2020

Кнопка Загрузить Стиль

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"/>

person user25775    schedule 09.01.2017
comment
Отличное решение! - person Samuel Ramzan; 29.08.2018
comment
Это не отображает имя файла и, следовательно, не отвечает на вопрос. - person KittMedia; 09.03.2020

У меня была длинная трещина, я надеюсь, что это поможет вам, возможно, вам придется стилизовать ее по своему вкусу.

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: https://jsfiddle.net/kd1brhny/

person PloxPanda    schedule 09.01.2017