确定上传的文件是否为MVC上的图像(任何格式)

所以我使用这个代码来查看:

<form action="" method="post" enctype="multipart/form-data"> <label for="file">Filename:</label> <input type="file" name="file" id="file" /> <input type="submit" /> </form> 

这为模型:

 [HttpPost] public ActionResult Index(HttpPostedFileBase file) { if (file.ContentLength > 0) { var fileName = Path.GetFileName(file.FileName); var path = Path.Combine(Server.MapPath("~/App_Data/uploads"), fileName); file.SaveAs(path); } return RedirectToAction("Index"); } 

很好的工作,除非用户添加一个不是图像的文件。 我怎样才能保证上传的文件是一个图像。 谢谢

万一它可以帮助任何人,这是一个HttpPostedFileBase静态方法,检查给定的上传文件是否是一个图像:

 public static class HttpPostedFileBaseExtensions { public const int ImageMinimumBytes = 512; public static bool IsImage(this HttpPostedFileBase postedFile) { //------------------------------------------- // Check the image mime types //------------------------------------------- if (postedFile.ContentType.ToLower() != "image/jpg" && postedFile.ContentType.ToLower() != "image/jpeg" && postedFile.ContentType.ToLower() != "image/pjpeg" && postedFile.ContentType.ToLower() != "image/gif" && postedFile.ContentType.ToLower() != "image/x-png" && postedFile.ContentType.ToLower() != "image/png") { return false; } //------------------------------------------- // Check the image extension //------------------------------------------- if (Path.GetExtension(postedFile.FileName).ToLower() != ".jpg" && Path.GetExtension(postedFile.FileName).ToLower() != ".png" && Path.GetExtension(postedFile.FileName).ToLower() != ".gif" && Path.GetExtension(postedFile.FileName).ToLower() != ".jpeg") { return false; } //------------------------------------------- // Attempt to read the file and check the first bytes //------------------------------------------- try { if (!postedFile.InputStream.CanRead) { return false; } if (postedFile.ContentLength < ImageMinimumBytes) { return false; } byte[] buffer = new byte[512]; postedFile.InputStream.Read(buffer, 0, 512); 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; } } 

编辑2/10/2017:根据build议的编辑,添加了最后的声明重置stream,所以我们可以稍后使用它。

手边没有编译器,但是应该这样做:

 try { var bitmap = Bitmap.FromStream( file.InputStream ); // valid image stream } catch { // not an image } 

在静态辅助类中使用:

 public static bool IsImage(HttpPostedFileBase postedFile) { try { using (var bitmap = new System.Drawing.Bitmap(postedFile.InputStream)) { return !bitmap.Size.IsEmpty; } } catch (Exception) { return false; } } } 

在ASP.NET MVC中使用viewmodel:

 public class UploadFileViewModel { public HttpPostedFileBase postedFile { get; set; } public bool IsImage() { try { using (var bitmap = new System.Drawing.Bitmap(this.postedFile.InputStream)) { return !bitmap.Size.IsEmpty; } } catch (Exception) { return false; } } } } 

这个例子检查图像是否是一个真实的图像,你可以修改和转换它。

它以6升V8的记忆为例,所以当你真的想知道这个图像时应该使用它。

对于遇到这个问题的人来说。

您也可以使用file.ContentType.Contains("image")来检查内容types是否为image / *。

 if(file.ContentLength > 0 && file.ContentType.Contains("image")) { //valid image } else { //not a valid image } 

不知道这是否是最佳做法,但对我有用。

作为第一步,您应该根据ContentType属性在可接受的MIMEtypes周围形成一个白名单。

以更清洁的方式实施,

 public static class FileExtensions { private static readonly IDictionary<string, string> ImageMimeDictionary = new Dictionary<string, string> { { ".bmp", "image/bmp" }, { ".dib", "image/bmp" }, { ".gif", "image/gif" }, { ".svg", "image/svg+xml" }, { ".jpe", "image/jpeg" }, { ".jpeg", "image/jpeg" }, { ".jpg", "image/jpeg" }, { ".png", "image/png" }, { ".pnz", "image/png" } }; public static bool IsImage(this string file) { if (string.IsNullOrEmpty(file)) { throw new ArgumentNullException(nameof(file)); } var extension = Path.GetExtension(file); return ImageMimeDictionary.ContainsKey(extension); } } 

在服务器端与内容types比较,如果它与您所需的上传格式匹配,然后继续或返回错误消息