Determine if uploaded file is image (any format) on MVC
In case it can helps anyone, Here is a static method for HttpPostedFileBase
that checks if a given uploaded file is an image:
public static class HttpPostedFileBaseExtensions
{
public const int ImageMinimumBytes = 512;
public static bool IsImage(this HttpPostedFileBase postedFile)
{
//-------------------------------------------
// Check the image mime types
//-------------------------------------------
if (!string.Equals(postedFile.ContentType, "image/jpg", StringComparison.OrdinalIgnoreCase) &&
!string.Equals(postedFile.ContentType, "image/jpeg", StringComparison.OrdinalIgnoreCase) &&
!string.Equals(postedFile.ContentType, "image/pjpeg", StringComparison.OrdinalIgnoreCase) &&
!string.Equals(postedFile.ContentType, "image/gif", StringComparison.OrdinalIgnoreCase) &&
!string.Equals(postedFile.ContentType, "image/x-png", StringComparison.OrdinalIgnoreCase) &&
!string.Equals(postedFile.ContentType, "image/png", StringComparison.OrdinalIgnoreCase))
{
return false;
}
//-------------------------------------------
// Check the image extension
//-------------------------------------------
var postedFileExtension = Path.GetExtension(postedFile.FileName);
if (!string.Equals(postedFileExtension , ".jpg", StringComparison.OrdinalIgnoreCase)
&& !string.Equals(postedFileExtension , ".png", StringComparison.OrdinalIgnoreCase)
&& !string.Equals(postedFileExtension , ".gif", StringComparison.OrdinalIgnoreCase)
&& !string.Equals(postedFileExtension , ".jpeg", StringComparison.OrdinalIgnoreCase))
{
return false;
}
//-------------------------------------------
// Attempt to read the file and check the first bytes
//-------------------------------------------
try
{
if (!postedFile.InputStream.CanRead)
{
return false;
}
//------------------------------------------
// Check whether the image size exceeding the limit or not
//------------------------------------------
if (postedFile.ContentLength < ImageMinimumBytes)
{
return false;
}
byte[] buffer = new byte[ImageMinimumBytes];
postedFile.InputStream.Read(buffer, 0, ImageMinimumBytes);
string content = System.Text.Encoding.UTF8.GetString(buffer);
if (Regex.IsMatch(content, @"<script|<html|<head|<title|<body|<pre|<table|<a\s+href|<img|<plaintext|<cross\-domain\-policy",
RegexOptions.IgnoreCase | RegexOptions.CultureInvariant | RegexOptions.Multiline))
{
return false;
}
}
catch (Exception)
{
return false;
}
//-------------------------------------------
// Try to instantiate new Bitmap, if .NET will throw exception
// we can assume that it's not a valid image
//-------------------------------------------
try
{
using (var bitmap = new System.Drawing.Bitmap(postedFile.InputStream))
{
}
}
catch (Exception)
{
return false;
}
finally
{
postedFile.InputStream.Position = 0;
}
return true;
}
}
Edit 2/10/2017: According to a suggested edit, added a finally statement to reset the stream, so we can use it later.
determine if file is an image
Check the file for a known header. (Info from link also mentioned in this answer)
The first eight bytes of a PNG file always contain the following (decimal) values: 137 80 78 71 13 10 26 10
How do I check if the uploaded file has the right format?
protected void Button1_Click(object sender, EventArgs e)
{
string strFileName = Path.GetFileName(FileUpload1.PostedFile.FileName);
string strFileWithoutExt = Path.GetFileNameWithoutExtension(strFileName);
string strExtension = Path.GetExtension(strFileName);
if (strExtension == ".jpg" || strExtension == ".bmp" || strExtension == ".gif")
{
string strImageFolder = "~/YourFilePath/";
if (!Directory.Exists(Server.MapPath(strImageFolder)))
Directory.CreateDirectory(Server.MapPath(strImageFolder));
string _strPath = Server.MapPath(strImageFolder) + strFileName;
FileUpload1.PostedFile.SaveAs(_strPath);
Label1.Text = "Upload status: File uploaded.";
}
else
Label1.Text = "Upload status: only .jpg,.bmp and .gif file are allowed!";
}
Hope Its Help You much more....
How to validate uploaded file in ASP.Net Core
You could custom validation attribute MaxFileSizeAttribute
like below
MaxFileSizeAttribute
public class MaxFileSizeAttribute : ValidationAttribute
{
private readonly int _maxFileSize;
public MaxFileSizeAttribute(int maxFileSize)
{
_maxFileSize = maxFileSize;
}
protected override ValidationResult IsValid(
object value, ValidationContext validationContext)
{
var file = value as IFormFile;
if (file != null)
{
if (file.Length > _maxFileSize)
{
return new ValidationResult(GetErrorMessage());
}
}
return ValidationResult.Success;
}
public string GetErrorMessage()
{
return $"Maximum allowed file size is { _maxFileSize} bytes.";
}
}
AllowedExtensionsAttribute
public class AllowedExtensionsAttribute : ValidationAttribute
{
private readonly string[] _extensions;
public AllowedExtensionsAttribute(string[] extensions)
{
_extensions = extensions;
}
protected override ValidationResult IsValid(
object value, ValidationContext validationContext)
{
var file = value as IFormFile;
if (file != null)
{
var extension = Path.GetExtension(file.FileName);
if (!_extensions.Contains(extension.ToLower()))
{
return new ValidationResult(GetErrorMessage());
}
}
return ValidationResult.Success;
}
public string GetErrorMessage()
{
return $"This photo extension is not allowed!";
}
}
Add MaxFileSize
attribute and AllowedExtensions
attribute to Photo
property
public class UserViewModel
{
[Required(ErrorMessage = "Please select a file.")]
[DataType(DataType.Upload)]
[MaxFileSize(5* 1024 * 1024)]
[AllowedExtensions(new string[] { ".jpg", ".png" })]
public IFormFile Photo { get; set; }
}
How to check if the uploaded image file is fake using ASP.NET C#?
As @Isma commented, define "broken".
But you can try to create a new System.Drawing.Image with it. If you want to validate anything else about it, then access it's properties. For instance you can check that the image is larger than 1 pixel if that suits your purpose. If an exception is thrown creating, or during your other checks, then it is (unlikely) a valid image.
private static bool CheckImage(string filename)
{
try
{
using (var image = Image.FromFile(filename))
{
if(image.Height<2 && image.Width<2)
return false
}
return true;
}
catch (Exception ex)
{
// probably should log more information here
return false;
}
}
How to check if the image file existed in mvc?
i guess my answer
@if (File.Exists(Server.MapPath("/Doctor/" + doctor.DoctorID + ".png")) && doctor.DoctorId > 0)
{
<img src="@Url.Content(String.Format("~/Doctor/" + doctor.DoctorID + ".png"))" />
}
else
{
<img src="~/img/avatar-sign.png" />
}
Data annotation for IFormFile so it only allows files with .png, .jpg or .jpeg extension
Use
public class AllowedExtensionsAttribute : ValidationAttribute
{
private readonly string[] _extensions;
public AllowedExtensionsAttribute(string[] extensions)
{
_extensions = extensions;
}
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
var file = value as IFormFile;
var extension = Path.GetExtension(file.FileName);
if (file != null)
{
if (!_extensions.Contains(extension.ToLower()))
{
return new ValidationResult(GetErrorMessage());
}
}
return ValidationResult.Success;
}
public string GetErrorMessage()
{
return $"Your image's filetype is not valid.";
}
}
put to your code
public class ProductViewModel
{
[Display(Name = "Image")]
[Required(ErrorMessage = "Pick an Image")]
[AllowedExtensions(new string[] { ".jpg", ".jpeg", ".png" })]
public IFormFile File { get; set; }
}
How to validate uploaded files in ASP.Net MVC
The first way is using IValidatableObject
:
public class UserViewModel : IValidatableObject
{
public IList<IFormFile> Photo { get; set; }
public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
var photos = ((UserViewModel)validationContext.ObjectInstance).Photo;
foreach(var photo in photos)
{
var extension = Path.GetExtension(photo.FileName);
var size = photo.Length;
if (!extension.ToLower().Equals(".jpg")||! extension.ToLower().Equals(".png"))
yield return new ValidationResult($"{photo.FileName}'s file extension is not valid.");
if (size > (5 * 1024 * 1024))
yield return new ValidationResult($"{photo.FileName}'s file size is bigger than 5MB.");
}
}
}
Result:
The second way is to custom validation attribute:
MaxFileSizeAttribute:
public class MaxFileSizeAttribute : ValidationAttribute
{
private readonly int _maxFileSize;
public MaxFileSizeAttribute(int maxFileSize)
{
_maxFileSize = maxFileSize;
}
protected override ValidationResult IsValid(
object value, ValidationContext validationContext)
{
var files = value as IList<IFormFile>;
foreach(var file in files)
{
if (file != null)
{
if (file.Length > _maxFileSize)
{
return new ValidationResult(GetErrorMessage(file.FileName));
}
}
}
return ValidationResult.Success;
}
public string GetErrorMessage(string name)
{
return $"{name}'s size is out of range.Maximum allowed file size is { _maxFileSize} bytes.";
}
}
AllowedExtensionsAttribute:
public class AllowedExtensionsAttribute : ValidationAttribute
{
private readonly string[] _extensions;
public AllowedExtensionsAttribute(string[] extensions)
{
_extensions = extensions;
}
protected override ValidationResult IsValid(
object value, ValidationContext validationContext)
{
var files = value as IList<IFormFile>;
foreach(var file in files)
{
var extension = Path.GetExtension(file.FileName);
if (file != null)
{
if (!_extensions.Contains(extension.ToLower()))
{
return new ValidationResult(GetErrorMessage(file.FileName));
}
}
}
return ValidationResult.Success;
}
public string GetErrorMessage(string name)
{
return $"{name} extension is not allowed!";
}
}
Model:
public class UserViewModel
{
[MaxFileSize(5 * 1024 * 1024)]
[AllowedExtensions(new string[] { ".jpg",".png"})]
public IList<IFormFile> Photo { get; set; }
}
View(Upload.cshtml):
@model UserViewModel
<form method="post"
asp-action="Upload"
asp-controller="Home"
enctype="multipart/form-data">
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<input asp-for="Photo" />
<span asp-validation-for="Photo" class="text-danger"></span>
<input type="submit" value="Upload" />
</form>
Controller:
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Upload(UserViewModel userViewModel)
{
if (!ModelState.IsValid)
{
return View("Upload");
}
return View("Index");
}
Related Topics
Web API 2: How to Return JSON with Camelcased Property Names, on Objects and Their Sub-Objects
C# "Internal" Access Modifier When Doing Unit Testing
What Are the Benefits of Using C# VS F# or F# VS C#
Inno Setup for Windows Service
How to Easily Initialize a List of Tuples
What Really Happens in a Try { Return X; } Finally { X = Null; } Statement
How to Find the Difference Between Two Images
Is Inaccessible Due to Its Protection Level
Displaying Arabic Characters in C# Console Application
Double Buffering When Not Drawing in Onpaint(): Why Doesn't It Work
Why Can't I Use System.Io.File Methods in an MVC Controller
Wpf: How to Override Part of a Controltemplate Without Redefining the Whole Style
How to Restrict/Control the Navigation Routes the User Can Visit Based on Login Status/Role
Outofmemoryexception While Populating Memorystream: 256Mb Allocation on 16Gb System
How to Read Data from a Zip File Without Having to Unzip the Entire File