skip to Main Content

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


  1. I think you misunderstood string interpolation. Instead of string Image = @"filepath"; you probably wanted to do string Image = $"{filepath}"; but that would just be the same as string Image = filepath; and you’d be creating a second variable that would be holding the same value as filepath.

    Instead, try removing that line and just do string Format = Path.GetExtension(filepath);

    Login or Signup to reply.
  2. You can retrieve uploaded Content Type (MIME) in controller and check corresponding format

     HttpFileCollection MyFileCollection = Request.Files;
    
     for (int Loop1 = 0; Loop1 < MyFileCollection.Count; Loop1++)
     {
        if (MyFileCollection[Loop1].ContentType == "image/jpeg")
        {
           //...
        }
     }
    

    Source: Microsoft Docs

    Login or Signup to reply.
  3. 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;

        public static bool ExtensionVerifier(string expectedExtension, IFormFile file)
    {
        
        var fileName = file.FileName.Split('.')[0];
            var fileExtension = file.FileName.Split('.')[file.FileName.Split('.').Length-1];
        var pExtension = expectedExtension.ToString().ToLower();
        
    
        #region Byte_Signatures_of_ImageTypes
    
        var ImageTypes = new Dictionary<string, string>();
        ImageTypes.Add("FFD8", "jpg");
        ImageTypes.Add("424D", "bmp");
        ImageTypes.Add("474946", "gif");
        ImageTypes.Add("89504E470D0A1A0A", "png");
    
        #endregion
    
    
        using (var signatureChecker = file.OpenReadStream())
        {
            signatureChecker.Seek(0, SeekOrigin.Begin);
            var builder = new StringBuilder();
            int byteHeader = ImageTypes.FirstOrDefault(img => img.Value == fileExtension).Key.Length;
    
            for (int i = 0; i < byteHeader; i += 2)
            {
                string bit = signatureChecker.ReadByte().ToString("X2");
                builder.Append(bit);
                string builtHex = builder.ToString();
                if (ImageTypes.ContainsKey(key: builtHex))
                {
                    if (fileExtension == pExtension)
                    {
                        signatureChecker.Dispose();
                        return true;
                    }
    
                }
    
            }
            return false;
        }
    
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search