I want to make a function that the user can choose a text file from a file picker and then it will read the file and do some stuff while reading... I'm having a lot of issues and can't make it work. It does not send back to the controller the correct path only "C:\fakepath\file.txt". I tried putting a real path manually in the function and it said that it can't find the file... I'm really stuck. This is my html file:
@using (Html.BeginForm("FilterFile", "Home",FormMethod.Post))
{
<div>
<input type="file" id="textFile">
</div>
<button id="submit-button" type="submit">Filter</button>
<script src="~/Scripts/jquery-3.3.1.min.js"></script>
}
<script>
$(document).ready(function () {
$('form').submit(function () {
$.ajax({
url: '@Url.Action("FilterFile")',
type: "POST",
dataType: "json",
contentType: "application/json; charset=utf-8",
data: JSON.stringify({
fileName: $('#textFile').val()
}),
success: function (result) {
},
error: function (result) {
alert("Failed");
}
});
return false;
});
});
This is my controller:
[HttpPost]
public JsonResult FilterFile(string fileName)
{
var resultMessage = "";
try
{
using (var sr = new StreamReader(fileName))
{
string line;
while ((line = sr.ReadLine()) != null)
{
if (line.Split(' ').Count() > 1)
{
var number = line.Split(' ')[0];
line.Replace(number, "");
}
}
}
resultMessage = "The task was completed successfully!!";
}
catch(Exception ex)
{
resultMessage = ex.Message;
}
return Json(resultMessage);
}
}
I would really appreciate if someone can help me since I'm new to programming.Thanks.