Search code examples
javascriptjquerydom

uncaught TypeError cannot read property '0'


I am trying to upload a file using javascript and asp.net mvc 5. But I am getting this error.

uncaught typeError cannot read property '0'

Here is my codes :

$("#btnReciveDocument").click(function (e) {
    e.preventDefault();
    debugger;
    var formdata = new FormData(); //FormData object
    var fileInput = $("#fileInput")

    //uncaught typeerror cannot read property '0'
    formdata.append(fileInput.files[0].name, fileInput.files[0]);

    var xhr = new XMLHttpRequest();
    xhr.open('POST', '/Home/Upload');
    xhr.send(formdata);
    xhr.onreadystatechange = function () {
        if (xhr.readyState == 4 && xhr.status == 200) {
            alert(xhr.responseText);
        }
    }
});

Solution

  • it is due to the fact that you are trying to access the property files of $("#fileInput"): equivalent to $("#fileInput").files, that has undefined as results.

    Without more knowledge of your DOM i cannot provide you a solution.