FileUpload:使用 JS 获取文件名不起作用

FileUpload: Get filenames with JS not working

我想获取文件名并将其放在标签 lbName 中,但此代码无效。我用了asp:FileUpload。这是我的代码:

<asp:FileUpload ID="FileUpload1" AllowMultiple="true" runat="server" Onchange="upload()"/> <asp:Label ID="lbName" runat="server" ForeColor="Gray" Visible="True"></asp:Label>

和JS代码:

function upload() {
    var name = "";

    var files = document.getElementById("<%= FileUpload1.ClientID %>");
    for (var i = 0; i < files.length; i++) {
        name = name + (files[i].name) + ";";
    }
    document.getElementById("lbName").value = "1: " + name;
}

您可以使用 jQuery 并将更改事件绑定到 input type=file

<script type="text/javascript">

    $('input[type="file"]').change(function (e) {
        var files = [];
        for (var i = 0; i < $(this)[0].files.length; i++) {
            files.push($(this)[0].files[i].name);
        }
        $(this).next('span').html(files.join(', '));
    });

</script>

或者,如果您想 javascript 工作:

<script type="text/javascript">

    function upload() {
        var name = "";
        var files = document.getElementById("<%= FileUpload1.ClientID %>");
        for (var i = 0; i < files.files.length; i++) {
            name = name + (files.files[i].name) + ";";
        }
        document.getElementById("<%= lbName.ClientID %>").innerHTML = "1: " + name;
    }

</script>