Skip to content
Advertisement

FileUpload: Get filenames with JS not working

I want to get filenames and put it in label lbName but this code is not working. I used asp:FileUpload. This is my code:

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

and JS code:

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

Advertisement

Answer

You could use jQuery and bind a change event to the 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>

Or if you want to make your javascript work:

<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>
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement