예제 #1
0
        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));
            }
        }
예제 #2
0
        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);
        }
        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);
        }
예제 #5
0
        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 GetFileType_ShouldReturnNullIfTheTypeIsUnknown()
        {
            using var fileStream = File.OpenRead("./files/test");

            IFileType expected = null;

            var actual = FileTypeValidator.GetFileType(fileStream);

            Assert.AreEqual(expected, actual);
        }
예제 #7
0
        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 GetFileType_ShouldThrowArgumentNullExceptionIfStreamIsNull()
 => Assert.Catch <ArgumentNullException>(() => FileTypeValidator.GetFileType(null));
예제 #9
0
        /// <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()));
        }