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

问题描述 投票:0回答:2

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

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;
    });
});

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

javascript image file file-upload image-uploading
2个回答
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>

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>
© www.soinside.com 2019 - 2024. All rights reserved.