How can I write a code in the Asp.net Core project to get the format of the photo file and accept only the jpg format and not any other format?
The code I wrote was this, but it didn’t work
pro.ItemId = pro.Id;
if (Product.Picture?.Length > 0)
{
string filepath = Path.Combine(Directory.GetCurrentDirectory(),
"wwwroot",
"image",
pro.Id + Path.GetExtension(Product.Picture.FileName));
// string Image = @"filepath";
string Format = Path.GetExtension(filepath);
if (Format == "jpg")
{
using (var stream = new FileStream(filepath, FileMode.Create))
{
Product.Picture.CopyTo(stream);
}
}
else
{
ModelState.AddModelError("Picture", "لطفا تصویر را با فرمت jpg انتخاب کنید.");
}
}
3
Answers
I think you misunderstood string interpolation. Instead of
string Image = @"filepath";
you probably wanted to dostring Image = $"{filepath}";
but that would just be the same asstring Image = filepath;
and you’d be creating a second variable that would be holding the same value asfilepath
.Instead, try removing that line and just do
string Format = Path.GetExtension(filepath);
You can retrieve uploaded Content Type (MIME) in controller and check corresponding format
Source: Microsoft Docs
You can actually check the byte signatures to verify if it’s jpg or any other image file by reading their byte stream, they begin with a unique byte header ex. jpg files begin with "FFD8".
I do actually have a method that covers 4 different image extensions and checks if the image is either jpg/png/bmp/gif;