jQuery File Upload Size Limit in Asp.Net Core MVC

How to restrict user to upload a file having size more than define limit using jQuery in asp.net core 8 mvc using c#.net. Get file size in controller.
In today's article I will show simple example with a tutorial to restrict the file upload size limit using jQuery in asp.net core mvc before upload of file. Here if user select file size more than limit at that time, he will get alert message and will not allow to upload the file, on other hand on selection of file with limited size he will allow to get the file detail in controller and upload the file in wwwroot folder in asp.net core 6 mvc using c#.net.

Now for this we will create a new asp.net core mvc application with c#.net. Here i have used .net core 8. Now we will add the model class file. 

 public class FileModel
{        
    public IFormFile File { get; set; }
    public string FileSize { get; set; }
} 
In above code i have defined two properties on os string type and second one is of IFormFile. Now we will create a folder in wwwroot folder, where we will upload the file. 

Folder in wwwroot

Now we will add an HttpGet method in the controller.
[HttpGet]
public IActionResult Index()
{
    FileModel fileModel = new FileModel();
    return View(fileModel);
} 
Here i have created the object of model class and pass it to the view. Now we will create a view. and add the below code.
 @model FileModel
@{
    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>
    <div>Max file size allowed: 1MB (1024KB)</div>
    <b>FILE SIZE</b>
    <div style="color:brown;font-weight:bold;">
        @Model.FileSize
    </div>
} 
<script>
    var ValidteFileSize = function () {
        var fsize = $("#filecontrol")[0].files[0].size;
        var sizeInKB=fsize/1024;
        if (sizeInKB > 1024) {
            $("#divmessage").html("File size more then 1MB or 1024KB.");
            return false;
        }
        return true;
    }
</script> 
Here in above code, I have added the model class reference in view. After page title you need to add 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.
I have added the form tag, which is having controller name and action name. In this you must add new { @enctype = "multipart/form-data" } otherwise you will not be able to get the selected file at controller end. After that I have taken div control to display the message. Here i have used the input control of file type to browse the file for upload. One thing you need to take care the input control of file type name must be same as the IFormFile type property. Last control is the submit button. 
Now we will check code for validating the size of uploaded file in jQuery.
 var ValidteFileSize = function () {
    var fsize = $("#filecontrol")[0].files[0].size;
    var sizeInKB=fsize/1024;
    if (sizeInKB > 1024) {
        $("#divmessage").html("File size more then 1MB or 1024KB.");
        return false;
    }
    return true;
} 
In above code i have created a function, in this function. First I have read the size of the uploaded file with $("#filecontrol")[0].files[0].size in jQuery. After that I have divided the total file size with 1024 to convert the byte to kilo byte.  In next line size validation taken place. If size is more than1024KB it will throw an exception message to user. If size is less than 1MB it will return true and form will post to controller. 
 [HttpPost]
public IActionResult Index(FileModel fileModel)
{
    if (fileModel.File != null)
    {
        try
        {
            string parentPath = @"wwwroot\Demofiles\";
            string uploadfilepath = Path.Combine(Directory.GetCurrentDirectory(), parentPath, fileModel.File.FileName);
            var filestream = new FileStream(uploadfilepath, FileMode.Create);
            fileModel.File.CopyToAsync(filestream);
            string dbSaveUploadPath = string.Format("{0}{1}", @"\Demofiles\", fileModel.File.FileName);
            fileModel.FileSize =Convert.ToInt32( fileModel.File.Length / 1024);
            ViewBag.Message = "File uploaded successfully.";
        }
        catch (Exception ex)
        {
            ViewBag.Message = ex.Message;
        }
    }
    else
    {
        ViewBag.Message = "Please select file to upload.";
    }
    return View(fileModel);
} 
In above controller HttpPost method I have uploaded the file in wwwroot folder. After uploading the file to get the uploaded file size at controller end fileModel.FileSize have been used. Now we have done lets run the code to check the output.

Select File to Upload
Now select the file having size more then 1MB.

File Error Message

Click on submit button. we will get the message.

File size error messsage

Now let's select a file with small size and upload it.

Upload file

Here is the elected file detail.

Select File in Asp.Net Core mvc
As we click on upload button, at controller end we will able to get the file and its size.

File size in Controller
Now let's press F5 to check thee output.

File uploaded successfully

Please check the wwwroot folder.

File in wwwroot Folder
jquery-file-upload-size-limit-in-asp-net-core-mvc.zip 3.8MB

Post a Comment