I am trying to implement file upload functionality with ASP.NET and jQuery. I use input file control and have 7 of them in my page. The page is an ASPX page with master page. Here is my code;
ASPX:
<div class="form-group">
<asp:Label runat="server" AssociatedControlID="file1" CssClass="col-md-3 control-label">File 1</asp:Label>
<div class="col-md-9">
<input type="file" id="file1" runat="server" class="filestyle" data-icon="false" data-buttonbefore="true" data-buttontext="Dosya Seç" data-placeholder="Dosya Seçilmedi">
</div>
</div>
<div class="form-group">
<asp:Label runat="server" AssociatedControlID="file2" CssClass="col-md-3 control-label">File 2</asp:Label>
<div class="col-md-9">
<input type="file" id="file2" runat="server" class="filestyle" data-icon="false" data-buttonbefore="true" data-buttontext="Dosya Seç" data-placeholder="Dosya Seçilmedi">
</div>
</div>
JavaScript:
$(document).ready(function () {
$("#btnUpload").click(function (event) {
var file1 = $("#<%=file1.ClientID %>").files[0];
var file2 = $("#<%=file2.ClientID %>").files[0];
var files = [file1, file2];
if (files.length > 0) {
var formData = new FormData();
for (var i = 0; i < files.length; i++) {
formData.append(files[i].name, files[i]);
}
var progressbarLabel = $('#progressBar-label');
var progressbarDiv = $('#progressbar');
$.ajax({
url: '../Util/UploadHandler.ashx',
method: 'post',
data: formData,
contentType: false,
processData: false,
success: function () {
progressbarLabel.text('Complete');
progressbarDiv.fadeOut(2000);
},
error: function (err) {
alert(err.statusText);
}
});
progressbarLabel.text('Uploading...');
progressbarDiv.progressbar({
value: false
}).fadeIn(500);
}
});
});
I got error when I press upload button stating that file1 is undefined.
I also tried
var file1 = $("#file1").files[0];
and file1 is undefined again.
How can I get file1 in JavaScript code?