-1

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);
        }
    }
});
5
  • 1
    fileInput.files returns undefined. You probably need var fileInput = $("#fileInput")[0] to get the HTML element, because otherwise you're handling a jQuery element. Commented Sep 19, 2019 at 8:10
  • Check what do you have inside fileInput because this means that you have empty array and you are trying to use first element of that array with fileInput.files[0].name Commented Sep 19, 2019 at 8:17
  • 1
    @vaske an empty array wouldn't throw an error that says there is no property 0, it would have complained about name. Moreover, jQuery objects do not have a files property, this is part of HTMLInputElement interface. You need to extract the HTMLElement from the jQuery wrapper or use the jQuery wrapper interface to get the files content Commented Sep 19, 2019 at 8:21
  • yeah you are right. Commented Sep 19, 2019 at 8:27
  • @VLAZ i have tried this method and its working fine thanks.. Commented Sep 19, 2019 at 8:28

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for suggestion i have tried with method '$("#fileInput")[0]' Which is perfect

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.