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);
        }
    }
});
phuzi
  • 12,078
  • 3
  • 26
  • 50
SameerUllah
  • 211
  • 3
  • 14
  • `fileInput.files` returns `undefined`. You probably need `var fileInput = $("#fileInput")[0]` to get the HTML element, because otherwise you're handling a jQuery element. – VLAZ Sep 19 '19 at 08: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` – vaske Sep 19 '19 at 08:17
  • @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](https://stackoverflow.com/questions/13747892/jquery-input-files-equivalent) – VLAZ Sep 19 '19 at 08:21
  • yeah you are right. – vaske Sep 19 '19 at 08:27
  • @VLAZ i have tried this method and its working fine thanks.. – SameerUllah Sep 19 '19 at 08:28

1 Answers1

0

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.

Greedo
  • 3,438
  • 1
  • 13
  • 28