MVC3 How to check if HttpPostedFileBase is an image

前端 未结 3 1869
野的像风
野的像风 2021-01-31 18:13

I have a controller like this:

public ActionResult Upload (int id, HttpPostedFileBase uploadFile)
{
....
}

How can I make sure that uploadFile

3条回答
  •  不思量自难忘°
    2021-01-31 18:40

    You could check the file name and extension and MIME type but that might not be reliable because the user could simply rename the file before uploading. Here's a reliable way to achieve that by looking at the contents of the file: https://stackoverflow.com/a/6388927/29407

    You could of course extend this to other known image type formats than PNG, like this:

    public class ValidateFileAttribute : RequiredAttribute
    {
        public override bool IsValid(object value)
        {
            var file = value as HttpPostedFileBase;
            if (file == null)
            {
                return false;
            }
    
            if (file.ContentLength > 1 * 1024 * 1024)
            {
                return false;
            }
    
            try
            {
                var allowedFormats = new[] 
                { 
                    ImageFormat.Jpeg, 
                    ImageFormat.Png, 
                    ImageFormat.Gif, 
                    ImageFormat.Bmp 
                };
    
                using (var img = Image.FromStream(file.InputStream))
                {
                    return allowedFormats.Contains(img.RawFormat);
                }
            }
            catch { }
            return false;
        }
    }
    

提交回复
热议问题