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);
}
}
});
fileInput.filesreturnsundefined. You probably needvar fileInput = $("#fileInput")[0]to get the HTML element, because otherwise you're handling a jQuery element.fileInputbecause this means that you have empty array and you are trying to use first element of that array withfileInput.files[0].name0, it would have complained aboutname. Moreover, jQuery objects do not have afilesproperty, this is part of HTMLInputElement interface. You need to extract the HTMLElement from the jQuery wrapper or use the jQuery wrapper interface to get thefilescontent