/// <summary> /// Validates that the file is from certain type /// </summary> /// <typeparam name="T">Type that implements FileType</typeparam> /// <param name="fileContent">File as stream</param> /// <returns>True if file match the desired type otherwise returns false.</returns> public static bool Is <T>(this Stream fileContent) where T : FileType, IFileType, new() { var instance = new T(); var match = FileTypeValidator.GetBestMatch(fileContent); return(match?.GetType() == instance.GetType()); }
public bool IsExtensionAllowed(CheckExtensionMethodEnum checkExtensionMethodEnum, Stream stream, string filename) { var isExtensionAllowed = false; if (stream == null) { return(isExtensionAllowed); } switch (checkExtensionMethodEnum) { case CheckExtensionMethodEnum.MagicNumberOwnImplementation: isExtensionAllowed = CheckByOwnImplementation(stream); break; case CheckExtensionMethodEnum.ExtensionFromFileName: isExtensionAllowed = CheckByFilename(filename); break; case CheckExtensionMethodEnum.FileTypeCheckerNuget: isExtensionAllowed = FileTypeValidator.IsImage(stream); break; default: break; } return(isExtensionAllowed); }
public static void Main() { // You can register your own custom types validation if its needed. FileTypeValidator.RegisterCustomTypes(typeof(MyCustomFileType).Assembly); for (int i = 1; i <= 12; i++) { using var fileStream = File.OpenRead($".\\files\\{i}"); var isRecognizableType = FileTypeValidator.IsTypeRecognizable(fileStream); if (!isRecognizableType) { Console.WriteLine("Unknown file"); Console.WriteLine(new string('=', 10)); continue; } IFileType fileType = FileTypeValidator.GetFileType(fileStream); Console.WriteLine("Is Image?: {0}", fileStream.IsImageAsync()); Console.WriteLine("Is Bitmap?: {0}", fileStream.IsAsync <Bitmap>()); Console.WriteLine("Type Name: {0}", fileType.Name); Console.WriteLine("Type Extension: {0}", fileType.Extension); Console.WriteLine(new string('=', 10)); } }
protected override ValidationResult IsValid( object value, ValidationContext validationContext) { if (!(value is IFormFile file)) { return(ValidationResult.Success); } using (var stream = new MemoryStream()) { file.CopyTo(stream); if (!FileTypeValidator.IsTypeRecognizable(stream)) { return(new ValidationResult(InvalidExtensionErrorMessage)); } var fileType = FileTypeValidator.GetFileType(stream); if (!extensions.Contains(fileType.Extension.ToLower())) { return(new ValidationResult(InvalidExtensionErrorMessage)); } } return(ValidationResult.Success); }
/// <summary> /// Checks that the particular type is supported. /// </summary> /// <param name="formFile">Object that implements IFormFile interface.</param> /// <returns>If current type is supported</returns> /// <exception cref="System.ArgumentException"></exception> /// <exception cref="System.ArgumentNullException"></exception> /// <exception cref="System.NotSupportedException"></exception> /// <exception cref="System.ObjectDisposedException"></exception> public static bool IsTypeRecognizable(IFormFile formFile) { DataValidator.ThrowIfNull(formFile, nameof(IFormFile)); var stream = formFile.ReadFileAsStream(); return(FileTypeValidator.IsTypeRecognizable(stream)); }
public void Is_ShouldReturnTrueIfTheTypesMatch() { using var fileStream = File.OpenRead("./files/test.bmp"); var expected = true; var actual = FileTypeValidator.Is <Bitmap>(fileStream); Assert.AreEqual(expected, actual); }
public void Is_ShouldReturnFalseIfTypesDidNotMatch() { using var fileStream = File.OpenRead("./files/test.bmp"); var expected = false; var actual = FileTypeValidator.Is <Gzip>(fileStream); Assert.AreEqual(expected, actual); }
public void GetFileType_ShouldReturnFileExtension(string filePath, string expectedFileExtension) { using var fileStream = File.OpenRead(filePath); var actualFileTypeExtension = FileTypeValidator.GetFileType(fileStream).Extension; Assert.AreEqual(expectedFileExtension, actualFileTypeExtension); }
public void GetFileType_ShouldReturnFileName(string filePath, string expectedFileTypeName) { using var fileStream = File.OpenRead(filePath); var actualFileTypeName = FileTypeValidator.GetFileType(fileStream).Name; Assert.AreEqual(expectedFileTypeName, actualFileTypeName); }
public ActionResult UploadTranscripts(IFormFile file) { string transcriptPath = Configuration.ConfigPath.TranscriptsPath; Log.Information("Begin UploadTranscripts Action : Uploading transcripts to {0}", transcriptPath); if (string.IsNullOrEmpty(transcriptPath)) { return(RedirectToAction("Index", "Configuration", new { error = 1 })); } if (file == null) { return(RedirectToAction("Transcripts", "Task")); } // Create the directory if it doesn't exist System.IO.Directory.CreateDirectory(transcriptPath); if (file.ContentType == "application/pdf" && file.Length > 0) { using (var ftStream = file.OpenReadStream()) { // Examine the file byte structure to validate the type IFileType fileType = FileTypeValidator.GetFileType(ftStream); Log.Information("Validating file type for transcripts"); string filePath = System.IO.Path.Combine(transcriptPath, "transcripts.pdf"); if (fileType.Extension == "pdf") { Log.Information("File type validated as pdf - Saving to disk at {0}", filePath); try { using (var stream = new FileStream(filePath, FileMode.Create)) { AsyncHelpers.RunSync(() => file.CopyToAsync(stream)); } // Fire off task to process the pdf BackgroundJob.Enqueue <IGenerateTranscripts>( generator => generator.Execute()); } catch (Exception e) { Log.Error(e, "Unable to save uploaded transcripts.pdf file"); } } { Log.Error("transcripts.pdf is not a pdf file"); } } } return(View()); }
public void IsTypeRecognizable_ShouldReturnTrueIfFileIsRecognized(string filePath) { using var fileStream = File.OpenRead(filePath); var expected = true; var actual = FileTypeValidator.IsTypeRecognizable(fileStream); Assert.AreEqual(expected, actual); }
public void IsTypeRecognizable_ShouldReturnFalseIfFormatIsUnknown() { using var fileStream = File.OpenRead("./files/test"); var expected = false; var actual = FileTypeValidator.IsTypeRecognizable(fileStream); Assert.AreEqual(expected, actual); }
public void GetFileType_ShouldReturnNullIfTheTypeIsUnknown() { using var fileStream = File.OpenRead("./files/test"); IFileType expected = null; var actual = FileTypeValidator.GetFileType(fileStream); Assert.AreEqual(expected, actual); }
/// <summary> /// Checks that the particular type is supported. /// </summary> /// <param name="formFile">Object that implements IFormFile interface.</param> /// <returns>If current type is supported</returns> /// <exception cref="System.ArgumentException"></exception> /// <exception cref="System.ArgumentNullException"></exception> /// <exception cref="System.NotSupportedException"></exception> /// <exception cref="System.ObjectDisposedException"></exception> public static bool IsTypeRecognizable(IEnumerable <IFormFile> formFiles) { DataValidator.ThrowIfNull(formFiles, nameof(IEnumerable <IFormFile>)); foreach (var formFile in formFiles) { var stream = formFile.ReadFileAsStream(); if (!FileTypeValidator.IsTypeRecognizable(stream)) { return(false); } } return(true); }
public void Then_correct_errors_are_returned(string input, string filetype, bool isValid) { var validator = new FileTypeValidator { ValidationDefinition = new ValidationDefinition() { ErrorMessage = "Incorrect FileType", Name = "FileType", Value = filetype } }; var question = new Question { QuestionId = "Q1" }; var errors = validator.Validate(question, new Answer { Value = input, QuestionId = question.QuestionId }); (errors.Count is 0).Should().Be(isValid); }
/// <summary> /// Determines whether a specified object is valid. (Overrides <see cref = "ValidationAttribute.IsValid(object)" />) /// </summary> /// <remarks> /// This method returns <c>true</c> if the <paramref name = "value" /> is null. /// It is assumed the <see cref = "RequiredAttribute" /> is used if the value may not be null. /// </remarks> /// <param name = "value">The object to validate.</param> /// <returns><c>true</c> if the value is null or valid, otherwise <c>false</c></returns> protected override ValidationResult IsValid(object value, ValidationContext validationContext) { if (!(value is IFormFile file)) { return(ValidationResult.Success); } using var stream = new MemoryStream(); file.CopyTo(stream); if (!FileTypeValidator.IsTypeRecognizable(stream)) { return(new ValidationResult(this.UnsupportedFileErrorMessage)); } if (!stream.IsImageAsync().ConfigureAwait(false).GetAwaiter().GetResult()) { return(new ValidationResult(this.ErrorMessage ?? this.InvalidFileTypeErrorMessage)); } return(ValidationResult.Success); }
/// <summary> /// Get details about current file type. /// </summary> /// <param name="formFile">Object that implements IFormFile interface.</param> /// <returns>Instance of <see cref="IFileType}"/> type.</returns> /// /// <exception cref="System.ArgumentException"></exception> /// <exception cref="System.ArgumentNullException"></exception> /// <exception cref="System.NotSupportedException"></exception> /// <exception cref="System.ObjectDisposedException"></exception> /// <exception cref="System.InvalidOperationException"></exception> public static IFileType GetFileType(IFormFile formFile) { DataValidator.ThrowIfNull(formFile, nameof(Stream)); return(FileTypeValidator.GetFileType(formFile.ReadFileAsStream())); }
public void IsTypeRecognizable_ShouldThrowArgumentNullExceptionIfStreamIsNull() => Assert.Catch <ArgumentNullException>(() => FileTypeValidator.IsTypeRecognizable(null));
public void Is_ShouldThrowExceptionIfStreamIsNull() => Assert.Catch <ArgumentNullException>(() => FileTypeValidator.Is <Bitmap>(null));
public void GetFileType_ShouldThrowArgumentNullExceptionIfStreamIsNull() => Assert.Catch <ArgumentNullException>(() => FileTypeValidator.GetFileType(null));
public async Task <object> Upload(IEnumerable <IFormFile> files, int questionid, int answersetid) { string attachPath = _configuration.ConfigPath.AttachmentPath; var profile = await _dataService.GetProfileAsync(); var aset = await _context.AnswerSet.Include(a => a.Answers) .FirstOrDefaultAsync(a => a.AnswerSetId == answersetid && a.ProfileId == profile.ProfileId); if (aset == null) { return(NotFound()); } var answer = aset.Answers.FirstOrDefault(a => a.QuestionId == questionid); if (answer == null) { answer = new Answer { AnswerSetId = aset.AnswerSetId, QuestionId = questionid }; } if (answer.FileAttachmentGroupId == null) { // We need to create a new file attachment group FileAttachmentGroup fg = new FileAttachmentGroup { ProfileId = profile.ProfileId }; _context.FileAttachmentGroup.Add(fg); await _context.SaveChangesAsync(); answer.FileAttachmentGroupId = fg.FileAttachmentGroupId; _context.Answer.Update(answer); await _context.SaveChangesAsync(); } //long totalsize = files.Sum(f => f.Length); // full path to file in temp location // var filePath = Path.GetTempFileName(); List <object> response = new List <object>(); foreach (var formFile in files) { if (formFile.Length > 0) { FileAttachment fa = new FileAttachment { FileAttachmentGroupId = (int)answer.FileAttachmentGroupId, FileName = Path.GetFileName(formFile.FileName), ContentType = formFile.ContentType, CreatedDate = DateTime.Now, Length = formFile.Length, SecureFileName = Path.GetRandomFileName() }; if (!fa.ContentType.StartsWith("image/") && fa.ContentType != "application/pdf") { continue; } List <string> pathParts = new List <string>(); pathParts.Add("" + DateTime.Now.Year); pathParts.Add("" + profile.ProfileId); pathParts.Add("" + fa.FileAttachmentGroupId); // Calculate the subpath based on the current year and the user's profile Id fa.FileSubPath = Path.Combine(pathParts.ToArray()); // Now let's build the correct filepath pathParts.Insert(0, attachPath); var filePath = Path.Combine(pathParts.ToArray()); // Create the directory if it doesn't exist Directory.CreateDirectory(filePath); // Now add the secure filename and build the full file path pathParts.Add(fa.SecureFileName); filePath = Path.Combine(pathParts.ToArray()); using (var ftStream = formFile.OpenReadStream()) { // Examine the file byte structure to validate the type IFileType fileType = FileTypeValidator.GetFileType(ftStream); switch (fileType.Extension) { case "jpg": case "png": case "gif": case "pdf": case "doc": case "docx": _context.FileAttachment.Add(fa); await _context.SaveChangesAsync(); using (var stream = new FileStream(filePath, FileMode.Create)) { await formFile.CopyToAsync(stream); } response.Add(new { status = "verified", attachid = fa.FileAttachmentId, uuid = fa.FileAttachmentUuid, fa.FileName }); break; default: response.Add(new { status = "invalid", uuid = "", fa.FileName }); break; } } } } return(response); }
public void Is_ShouldThrowExceptionIfStreamIsNull() => Assert.Catch <ArgumentNullException>(() => FileTypeValidator.IsAsync <Bitmap>(null).GetAwaiter().GetResult());