What are the best practices to validate Image and upload in ASP.Net Core/EF Core?

.net .net-core c# entity-framework-core image-upload

Question

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 ?

1
0
3/25/2018 5:40:39 AM

Popular Answer

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

1
3/25/2018 9:25:19 AM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow