Restrict to Upload Only PDF File in ASP.NET Core MVC Using jQuery

How to restrict or validate or check or block user to upload only PDF file in asp.net core 8 mvc application using jQuery and c#.net with IFormFile.
In today's article I will show a simple tutorial with example how you can restrict or block a user to upload only the PDF(.pdf) 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 () {
        var fext = $("#filecontrol").val().split('.').pop();
        if (fext != 'pdf') {
            $("#divmessage").html("File type .pdf 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 () {
        var fext = $("#filecontrol").val().split('.').pop();
        if (fext != 'pdf') {
            $("#divmessage").html("File type .pdf is only allowed to upload.");
            return false;
        }
        return true;
    }
</script> 
In above code I have extracted the file extension by using jQuery. In next line I have validated the file extension, If the file extension is pdf 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 extention 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 text file (.txt).

Select Text file

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

Select correct file

Now let's select the PDF file and click on upload button.

PDF selected file to upload

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. 

Code to upload only PDF in asp.net core mvc

Now click on upload button to check the output.

PDF file uploaded successfully in asp.net core mvc

Now let's check the upload folder.

Uploaded PDF file in wwwroot folder

Post a Comment