Validation in ASP.NET MVC File Upload

26 Aug 202610 minutes to read

The Uploader control validates the selected file’s size and extension using the allowedExtensions, minFileSize and maxFileSize properties. The files can be validated before uploading to the server and ignored during upload. Additionally, you can validate the files by setting the HTML attributes on the input element. The validation process also occurs when you drag and drop the files.

File type

You can allow only specific files to be Uploaded using the allowedExtensions property. The extension can be specified as a comma-separated list. The uploader control filters the selected or dropped files to match the specified file types and processes the upload operation. The validation also occurs when you specify a value as an inline attribute on the original input element.

@Html.EJS().Uploader("UploadFiles").AllowedExtensions(".doc, .docx, .xls, .xlsx").AutoUpload(false).AsyncSettings(new Syncfusion.EJ2.Inputs.UploaderAsyncSettings { SaveUrl = "https://services.syncfusion.com/aspnet/production/api/FileUploader/Save", RemoveUrl = "https://services.syncfusion.com/aspnet/production/api/FileUploader/Remove" }).Render()
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;

namespace EJ2CoreSampleBrowser.Controllers.TextBoxes
{
    public class UploaderController : Controller
    {
        public ActionResult DefaultFunctionalities()
        {
            return View();
        }
    }
}

Output be like the below.

uploader

File size

The Uploader control allows you to validate the files based on their size. The validation helps to restrict uploading large or empty files to the server. The file size is measured in bytes. By default, the Uploader control allows you to upload files with a minimum file size of 0 bytes and a maximum file size of 28.4 MB, using the minFileSize and maxFileSize properties.

@Html.EJS().Uploader("UploadFiles").MinFileSize(10000).MaxFileSize(1000000).AsyncSettings(new Syncfusion.EJ2.Inputs.UploaderAsyncSettings { SaveUrl = "https://services.syncfusion.com/aspnet/production/api/FileUploader/Save", RemoveUrl = "https://services.syncfusion.com/aspnet/production/api/FileUploader/Remove" }).Render()
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;

namespace EJ2CoreSampleBrowser.Controllers.TextBoxes
{
    public partial class UploaderController : Controller
    {
        public ActionResult DefaultFunctionalities()
        {
            return View();
        }
    }
}

The output will be as shown below.

uploader

Maximum files count

You can restrict uploading the maximum number of files using the selected event. In the selected event arguments, you can get the details of currently selected files using getFilesData(). You can modify the files’ details and assign the modified file list to eventArgs.modifiedFilesData.

@Html.EJS().Uploader("UploadFiles").Selected("onFileSelected").Success("onUploadSuccess").AsyncSettings(new Syncfusion.EJ2.Inputs.UploaderAsyncSettings { SaveUrl = "https://services.syncfusion.com/aspnet/production/api/FileUploader/Save", RemoveUrl = "https://services.syncfusion.com/aspnet/production/api/FileUploader/Remove" }).Render()
<script>
    function onFileSelected(args) {
        // Filter the 5 files only to showcase
        var uploadObj = document.getElementById("UploadFiles")
        args.filesData.splice(5);
        var filesData = uploadObj.ej2_instances[0].getFilesData();
        var allFiles = filesData.concat(args.filesData);
        if (allFiles.length > 5) {
            for (var i = 0; i < allFiles.length; i++) {
                if (allFiles.length > 5) {
                    allFiles.shift();
                }
            }
            args.filesData = allFiles;
            // set the modified custom data
            args.modifiedFilesData = args.filesData;
        }
        args.isModified = true;
    }
    function onUploadSuccess(args) {
        var _this = this;
        var li = this.uploadWrapper.querySelector('[data-file-name="' + args.file.name + '"]');
        if (args.operation === 'upload') {
            li.querySelector('.e-file-delete-btn').onclick = function () {
                generateSpinner(_this.uploadWrapper);
            };
            li.querySelector('.e-file-delete-btn').onkeydown = function (e) {
                if (e.keyCode === 13) {
                    generateSpinner(e.target.closest('.e-upload'));
                }
            };
        }
        else {
            ej.popups.hideSpinner(this.uploadWrapper);
            ej.base.detach(this.uploadWrapper.querySelector('.e-spinner-pane'));
        }
    }
    function generateSpinner(targetElement) {
        ej.popups.createSpinner({ target: targetElement, width: '25px' });
        ej.popups.showSpinner(targetElement);
    }
</script>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;

namespace EJ2CoreSampleBrowser.Controllers.TextBoxes
{
    public partial class UploaderController : Controller
    {
        public ActionResult DefaultFunctionalities()
        {
            return View();
        }
    }
}

Duplicate files

You can check for duplicate files before uploading them to the server using the selected event. Compare the selected files with the existing files data and filter the file list to remove the duplicate files.

@Html.EJS().Uploader("UploadFiles").Selected("onFileSelected").AutoUpload(false).AsyncSettings(new Syncfusion.EJ2.Inputs.UploaderAsyncSettings { SaveUrl = "https://services.syncfusion.com/aspnet/production/api/FileUploader/Save", RemoveUrl = "https://services.syncfusion.com/aspnet/production/api/FileUploader/Remove" }).Render()
<script>
    function onFileSelected(args) {
        var isNullOrUndefined = ej.base.isNullOrUndefined;
        let existingFiles = this.getFilesData();
        for ( i = 0; i < args.filesData.length; i++) {
            for ( j = 0; j < existingFiles.length; j++) {
                if (!isNullOrUndefined(args.filesData[i])) {
                    if (existingFiles[j].name == args.filesData[i].name) {
                        args.filesData.splice(i, 1);
                    }
                }
            }
        }
        existingFiles = existingFiles.concat(args.filesData);
        args.modifiedFilesData = existingFiles;
        args.isModified = true;
    }
</script>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;

namespace EJ2CoreSampleBrowser.Controllers.TextBoxes
{
    public partial class UploaderController : Controller
    {
        public ActionResult DefaultFunctionalities()
        {
            return View();
        }
    }
}

See also