将按钮“选择文件”文本更改为文件名

时间:2018-09-18 09:29:26

标签: javascript image file file-upload image-uploading

我正在尝试为文件选择器自定义“选择文件”按钮。为了表明已选择文件,我希望将“选择文件”文本更改为文件名。这是我尝试过的:

var inputs = document.querySelectorAll( '.inputfile' );
Array.prototype.forEach.call( inputs, function( input )
{
    var label    = input.nextElementSibling,
        labelVal = label.innerHTML;

    input.addEventListener( 'change', function( e )
    {
        var fileName = '';
        if( this.files && this.files.length > 1 )
            fileName = ( this.getAttribute( 'data-multiple-caption' ) || '' ).replace( '{count}', this.files.length );
        else
            fileName = e.target.value.split( '\\' ).pop();

        if( fileName )
            label.querySelector( 'span' ).innerHTML = fileName;
        else
            label.innerHTML = labelVal;
    });
});

但是它不起作用,选择文件后没有任何改变。

2 个答案:

答案 0 :(得分:0)

const fileBlocks = document.querySelectorAll('.file-block')
const buttons = document.querySelectorAll('.btn-select-file')

;[...buttons].forEach(function (btn) {
  btn.onclick = function () {
    btn.parentElement.querySelector('input[type="file"]').click()
  }
})

;[...fileBlocks].forEach(function (block) {
  block.querySelector('input[type="file"]').onchange = function () {
    const filename = this.files[0].name

    block.querySelector('.btn-select-file').textContent = filename
  }
})
input[type="file"] {
  display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="file-block">
  <button class="btn-select-file">Select Image 1</button>
  <input type="file">
</div>
<br>
<div class="file-block">
  <button class="btn-select-file">Select Image 2</button>
  <input type="file">
</div>

答案 1 :(得分:0)

<!DOCTYPE html>
<html>

<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>JS Bin</title>
</head>

<body>
  <button style="display:block;width:120px; height:30px;" onclick="document.getElementById('getFile').click()">File Name</button>
  <input type='file' id="getFile" style="display:none">
</body>

</html>