Skip to content

This library adds an extension method to FileInfo & IFormFile to validate the file based on thier configuration(s).

License

Notifications You must be signed in to change notification settings

mak-thevar/FileValidator

Repository files navigation

Build Status LinkedIn

FileValidator

FileValidator is a .NET library that adds extension methods to both FileInfo and IFormFile. It helps you verify files against certain rules, such as size limits, allowed extensions, and MIME types. By default, it checks for documents, images, videos, and audio files, but you can easily customize it.

Installation

Usage

⚙️Using IFormFile on ActionMethod

  public async Task<IActionResult> OnPostUploadAsync(IFormFile file)
  {
      /*By default it validates all the files like Documents,Images, Videos, Audios*/
      bool isValid = file.IsValidFile();
      if(isValid){
          var filePath = Path.GetTempFileName();
          await file.CopyToAsync(File.OpenWrite(filePath));
          return Ok(new { message = "File uploaded successfully." });
      }
      return BadRequest(new {message = "Invalid file"});
      
  }

⚙️Using FileInfo Directly

var fileInfo = new FileInfo("C:/mypath/myimage.jpg");
var isValid = fileInfo.IsValidFile();
//If you want to only validate the Images then you can pass the allowed FileType[] parameter.
var checkValidImage = fileInfo.IsValidFile([ FileType.Image ])

⚙️Updating the default configuration (You can add or remove file extensions and MIME types as needed)

var fileInfo = new FileInfo("C:/mypath/document.pdf");

// Create a configuration and allow JSON as a document type
var fileValidatorConfig = new FileValidatorConfiguration();
fileValidatorConfig.DocumentFileExtensins.Add(".json");
fileValidatorConfig.DocumentMimeTypes.Add("application/json");
FileValidatorExtension.UpdateDefaultConfiguration(fileValidatorConfig);

// Now .json files will pass validation as documents
bool isValid = fileInfo.IsValidFile(); 

// Removing a known file type (for example, GIF in images)
fileValidatorConfig.ImmageFileExtensions.Remove(".gif");
FileValidatorExtension.UpdateDefaultConfiguration(fileValidatorConfig);

// GIF files will now fail validation

Contributing

Contributions are what make the open source community such an amazing place to be learn, inspire, and create. Any contributions you make are greatly appreciated. Feel free to request for any changes or any additional features.

License

Distributed under the MIT License. See LICENSE for more information.

Contact

About

This library adds an extension method to FileInfo & IFormFile to validate the file based on thier configuration(s).

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages