1

I have found some questions like Validate Image Type but it didn't fulfill my needs.
I have Model class named Movie which contains property

public byte[] Image { get; set; }

My View contains

<form asp-action="Index" method="post" enctype="multipart/form-data">
  <input asp-for="Image" type="file" id="files" class="form-control" />
  <input type="submit" value="Create" class="btn btn-default" />
</form>

and in controller, I am converting it to bytes and storing it in database. I want to validate it like, Files allowed .jpg, .jpeg, .png and max size of file 5Mb.

[HttpPost]
    public async Task<IActionResult> Index(Movie Movie, List<IFormFile> Image)
    {
        foreach(var item in Image)
        {
            if (item.Length > 0)
            {
                using (var stream = new MemoryStream())
                {
                    await item.CopyToAsync(stream);
                    Movie.Image = stream.ToArray();
                }
            }
        }
        _applicationDbContext.Movie.Add(Movie);
        _applicationDbContext.SaveChanges();
        return View();
    }

How can I validate the uploaded file ?

Fawad Bin Tariq
  • 164
  • 1
  • 3
  • 16

1 Answers1

1

Every file has an extension and if it is a binary file, it has magic numbers in the header of the file that indicates what type of file it is, You can identify file type by reading the header of bytes.

Check this GitHub code
https://github.com/Muraad/Mime-Detective

file headers reference:
http://www.garykessler.net/library/file_sigs.html

mime types reference:
http://www.webmaster-toolkit.com/mime-types.shtml

ElasticCode
  • 7,311
  • 2
  • 34
  • 45