简体   繁体   中英

How to do server side validation for byte type image file in C#

How to make server side validation for byte type. I have to upload image file and for that I have used byte. But when i do not upload image, it throws error which is normal behavior but the problem arises when I supply image and upload and submit it, the message still appears. How to remove that message after image upload.

.Class file

  public class EmailModel
  {        
    [Display(Name = "Attach photo")]
    [Required(ErrorMessage = "Please upload image")]
    public byte[] Photo { get; set; }
   }

index file

<input type="file" name="ImageData" id="ImageData" onchange="fileCheck(this);" />
@Html.ValidationMessageFor(m => m.Photo, "", new { @class = "text-danger" })

After submit the form, I have used this code to clear that validation error message in controller section

Array.Clear(emailvalues.Photo, 0,emailvalues.Photo.Length);

You can create custom validate attribute

 public class ImageCheckAttribute : ValidationAttribute
    {

        protected override ValidationResult IsValid(object value, ValidationContext validationContext)
        {

            try
            {
                using (MemoryStream ms = new MemoryStream((byte[])value))
                    Image.FromStream(ms);
            }
            catch (ArgumentException)
            {
                return new ValidationResult(this.FormatErrorMessage(validationContext.DisplayName));
            }
            return null;
        }
    }

And use

[Display(Name = "Attach photo")]
    [Required(ErrorMessage = "Please upload image")]
    [ImageCheck(ErrorMessage = "Byte array is incorrect image")]
    public byte[] Photo { get; set; }
   }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM