Restrict User to Upload Excel File in Asp.net Core MVC Using jQuery

How to restrict or block user to upload only excel file in asp.net core mvc using jQuery and C#.Net. IFormFile to get file in controller to upload.
In today's article I will show a simple tutorial with example how you can restrict or block a user to upload only the excel (.xlsx, .xls) file using jQuery in asp.net core 8 mvc using c#.net with IFormFile. For this article first we will create a new asp.net core mvc application with c#.net and create a folder in wwwroot folder

New Folder in wwwroot

After this we will add a controller file and add a HttpGet method as Index(). This HttpGet method act as a page load for your asp.net core mvc application. 

[HttpGet]
public IActionResult Index()
{
    return View();
} 
In above code I have define a method with return type as IActionResult with HttpGet method. Now lets create a view. In a view we will add our all Html code base. 
 @{
    ViewData["Title"] = "Home Page";
        <script src="~/lib/jquery/dist/jquery.min.js"></script>
}
@using (Html.BeginForm("Index", "Home", FormMethod.Post, new { @enctype = "multipart/form-data" }))
{
    <div style="color:red" id="divmessage">@ViewBag.Message</div>
    <div style="font-weight:bold;">Select File:</div>
    <div>
        <input type="file" class="form-control" name="file" id="filecontrol" />
    </div>
    <br />
    <div>
        <input type="submit" value="Upload File" onclick="javascript: return ValidteFileSize();" />
    </div>
}
<script>
    var ValidteFileSize = function () {
		const fileExtentions = ["xls", "xlsx"];
		var fext = $("#filecontrol").val().split('.').pop();
		if (!fileExtentions.includes(fext))                
            $("#divmessage").html("Excel file type .xls or .xlsx is only allowed to upload.");
            return false;
        }
        return true;
    }
</script>  
Here in above code, I have added the jQuery reference. Here I have added in the view but you need to add in the Layout page. to keep it common. You can download the jQuery library from given url.
In above code after adding the jQuery reference check the form tag. 
@using (Html.BeginForm("Index", "Home", FormMethod.Post, new { @enctype = "multipart/form-data" }))
Here Html.BeginForm methos is used for defining the form tag. In this method we need to add the Action name and the controller name and Form Method Type as Post. This piece of code will define that when user click on submit button which method need to execute at controller end.  Here one of the most important thing which we need to take care new { @enctype = "multipart/form-data" }. If we don't add this html attribute, we will not be able to get the selected file at the controller end. 

In next line I have taken the div control to display the message. Here I have taken the @ViewBag.Message to display the message send from controller end. In next line I have taken the input control of file type. to upload the browse the file. Here I have taken the file control name as name='file'. This name of the file must be same as the parameter passed to the HttpPost  method. In next line i have taken the Submit to submit the file to upload.

Please refer the below jQuery code.
<script>
    var ValidteFileSize = function () {
		const fileExtentions = ["xls", "xlsx"];
		var fext = $("#filecontrol").val().split('.').pop();
		if (!fileExtentions.includes(fext))                 
            $("#divmessage").html("Excel file type .xls or .xlsx is only allowed to upload.");
return false; } return true; } </script>
In above code I have taken an array with excel file extensions. If you want to add more or want to reduce the exitron you can do it in the array list. After defining the array of file extensions. I have extracted the file extension by using jQuery. In next line I have validated the file extension, If the file extension is xls or xlsx on that case return true otherwise return false with a user-friendly message to user. Here $("#filecontrol").val().split('.').pop() code is used for getting the selected file extension. On click of submit button I have called the file extension validation method which is as follows "onclick="javascript: return ValidteFileSize();". 

Now add the below code for HttpPost method. 
 [HttpPost]
public IActionResult Index(IFormFile file)
{
    if (file != null)
    {
        try
        {
            string parentPath = @"wwwroot\Demofiles\";
            string uploadfilepath = Path.Combine(Directory.GetCurrentDirectory(), parentPath, file.FileName);
            var filestream = new FileStream(uploadfilepath, FileMode.Create);
            file.CopyToAsync(filestream);
            string dbSaveUploadPath = string.Format("{0}{1}", @"\Demofiles\", file.FileName);
            ViewBag.Message = "File uploaded successfully.";
        }
        catch (Exception ex)
        {
            ViewBag.Message = ex.Message;
        }
    }
    else
    {
        ViewBag.Message = "Please select file to upload.";
    }
    return View();
} 
In above code you can check the passed parameter name. It is same as the file upload control name. after that validation for file is selected or not is applied. After that I have prepared the path to upload the file. FileStream(path, FileMode.Create) is used to create the filestream. After that I have used CopyToAsync to make the copy of the file in the specified file. In View bag I have added to message to display at user end. Now we have done run the code and select a pdf file.
File Upload in Asp.Net Core
Now select a non-excel file. Let's select a pdf or text file.

pdf File Selected to Upload

Now click on button to upload the file, we will get the error.

Excel file upload error

Now let's select the xls or xlsx file and click on upload button.

Excel Fil to Upload in Asp.net core mvc

Here you can see the file we have uploaded, we are getting at controller end. Here one you must notice that the passed parameter name and the file upload input control name is same. If you don't keep both things same, you will not be able to get the uploaded file detail at controller end. 

Selected File Detail at Controller in Asp.net core mvc

Now click on upload button to check the output.
File Uploaded Successfully in Asp.Net Core

Now let's check the upload folder.

Excel file in wwwroot folder
If you like the article and it is helpful to you, please let me know in comment.

Post a Comment