Reputation: 25370
I want to validate a file being uploaded via Ajax before the user can submit it. I make sure it is a .txt or .csv in javascript, then I want to call my controller to verify it matches our CSV standard.
I have :
<input type="file" name="csvFile" id="csvFile" onchange="validateFile()"/>
and
function validateFile() {
var file = document.getElementById("csvFile");
var extension = file.value.split('.').pop();
if (extension != "csv" && extension != "txt") {
alert("A .csv or .txt file is required for upload");
return false;
}
$.ajax({
url: '@Url.Action( "ValidateCSV","UploadCSV")',
type: "POST",
data: { file: document.getElementById("csvFile") }, //unclear here
success: function () {
alert("success");
},
error: function (error) {
alert("failed:" + error);
}
});
}
for the ajax data, how do i go about getting the HttpPostedFileBase
that the controller wants from the file? I was wanting to do all the validation before the user is allowed to submit it. I'm not 100% that I'm 'allowed' to do this
Thankyou for any guidance
Upvotes: 2
Views: 898
Reputation: 5577
Have you tried to put the input in a form?
<form action="" method="post" enctype="multipart/form-data">
<input type="file" name="csvFile" id="csvFile" class="file" onchange="changeFile();validFile();" />
<div class="fakefile">
<input id="csvFileFakeId" />
<button onclick="return false;" class="blue">Browse</button>
</div>
<button type="submit">Upload</button>
</form>
Validate the file type, if invalid, clear the input and alert the user.
<script type="text/javascript">
var fileId = "csvFile";
var fakeFileId = "csvFileFakeId";
function changeFile() {
var value = $("#" + fileId).val().split('\\').pop();
$("#" + fakeFileId).val(value);
};
function validateFile() {
var file = document.getElementById("csvFile");
var extension = file.value.split('.').pop();
if (extension != "csv" && extension != "txt") {
alert("A .csv or .txt file is required for upload");
$('#csvFile').val('');
$('#csvFileFakeId').val('');
return false;
}
};
</script>
And when the post the form (this assumes the MVC endpoint is Upload
or you have mapped that path
[HttpPost]
public ActionResult Upload(HttpPostedFileBase file)
{
....
}
Upvotes: 1
Reputation: 1898
I have an answer here using HTML5 file api. Upload photo with jQuery Dialog in ASP.NET MVC site
it was down voted but I always use it for uploading and it works.
Upvotes: 0