C# MVC3 如何检查 HttpPostedFileBase 是否是图像
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12120135/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
MVC3 How to check if HttpPostedFileBase is an image
提问by Henrik Stenb?k
I have a controller like this:
我有一个这样的控制器:
public ActionResult Upload (int id, HttpPostedFileBase uploadFile)
{
....
}
How can I make sure that uploadFile is an image (jpg, png etc.)
如何确保 uploadFile 是图像(jpg、png 等)
I have tried with
我试过
using (var bitmapImage = new Bitmap (uploadFile.InputStream)) {..}
which throws an ArgumentException if bitmapImage can not be created.
如果无法创建 bitmapImage,则会引发 ArgumentException。
Is there a better way for example by looking at uploadFile.FileName?
有没有更好的方法,例如查看uploadFile.FileName?
采纳答案by Yasser Shaikh
You can check the HttpPostedFileBaseobject's properties for this
您可以HttpPostedFileBase为此检查对象的属性
- ContentType
- FileName (check the file extensions, which you already know about :) )
- 内容类型
- FileName(检查您已经知道的文件扩展名:))


Also here is a small method, I have prepared which you can use/extend...
这里还有一个小方法,我已经准备好了,你可以使用/扩展......
private bool IsImage(HttpPostedFileBase file)
{
if (file.ContentType.Contains("image"))
{
return true;
}
string[] formats = new string[] { ".jpg", ".png", ".gif", ".jpeg" }; // add more if u like...
// linq from Henrik Stenb?k
return formats.Any(item => file.FileName.EndsWith(item, StringComparison.OrdinalIgnoreCase));
}
I have also written an article on this here
我也在这里写了一篇关于这个的文章
回答by Darin Dimitrov
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
您可以检查文件名和扩展名以及 MIME 类型,但这可能不可靠,因为用户可以在上传之前简单地重命名文件。这是通过查看文件内容来实现这一目标的可靠方法:https: //stackoverflow.com/a/6388927/29407
You could of course extend this to other known image type formats than PNG, like this:
您当然可以将其扩展到 PNG 以外的其他已知图像类型格式,如下所示:
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;
}
}
回答by Kristian Jay
Or you can check it on client side thru html attribute 'accept' to filter the file asap:
或者您可以通过 html 属性“接受”在客户端检查它以尽快过滤文件:
@Html.TextBoxFor(x => x.HomeDeviceImage, new { @type = "file", @accept = "image/x-png, image/gif, image/jpeg" })
this will only show filetypes defined in your accept attribute as default. Beware, user can still change filetye to "All files", with this in mind, better check this:
这只会显示在您的 accept 属性中定义的文件类型作为默认值。请注意,用户仍然可以将 filetye 更改为“所有文件”,考虑到这一点,最好检查一下:
Solved concern, a javascript snippet to check extension, and then do some editing to disable button like:
解决了问题,一个用于检查扩展的 javascript 片段,然后进行一些编辑以禁用按钮,例如:
$('input:submit').attr('disabled', true);
until file extension is correct. nevertheless have it checked on server side. :)
直到文件扩展名正确。尽管如此,请在服务器端检查它。:)

