document.getElementById(“ FileUpload1”);在IE

时间:2019-09-24 05:17:59

标签: javascript html

我在Chrome浏览器中获取文件名,但在IE中却获取了空值。 我只想在asp.net html和Java脚本中显示选择文件名。 随附的代码位于

var files = document.getElementById("FileUpload1");

给我空值/未定义的值,并且

var fileName = document.getElementById("FileUpload1").files[0].name

给出错误,因为无法获取未定义或空引用的属性“ 0”

function showFileName() { 
    document.getElementById("FileUploadedLabel").style.color = "black";
    var files = document.getElementById("FileUpload1"); 
    if(files != null && files != undefined && files != 'undefined') { 
        var fileName = document.getElementById("FileUpload1").files[0].name; 
        document.getElementById("FileUploadedLabel").innerHTML = "File name:-" + fileName;
    } 
}
<div class="image-upload">
    <label for="FileUpload1">
        <img src="button_choose-file.png" class="image" style="height:30px; width:100px" />
    </label>
    <asp:FileUpload runat="server" ID="FileUpload1" Style=" display:none;" onmouseover="mouseOverUpload()" onmouseout="mouseOutUpload()" Onchange="showFileName()"/>
</div>

1 个答案:

答案 0 :(得分:0)

<html>
    <head>
    <script>
    function showFileName(fileInput) {
    var files = ((typeof fileInput === 'string' && (fileInput = fileInput.match(/[^\\\/]+$/)) && fileInput[0]) || '')
    document.getElementById("FileUploadedLabel").innerHTML = "File name:" + files;
    }
    </script>
    </head>
    <body>
    <asp:FileUpload runat="server" ID="FileUpload1" Onchange="showFileName(this.value)"/>
    </html>
    </body>