MVC3如何检查HttpPostedFileBase是否是一个图像 [英] MVC3 How to check if HttpPostedFileBase is an image
问题描述
我有一个这样的控制器:
$ b $ pre $ public ActionResult上传(int id,HttpPostedFileBase uploadFile)
{
...
}
如何确保uploadFile是图片(jpg,png等)
我曾尝试使用
使用(var bitmapImage =新的位图(uploadFile.InputStream)){..}
ArgumentException如果无法创建bitmapImage。
有没有更好的方法,例如通过查看uploadFile.FileName?
您可以检查 HttpPostedFileBase
对象的属性为此
- ContentType
- FileName(检查文件扩展名,您已经知道了:))
这里还有一个小方法,我已经准备好你可以使用/扩展...
pre $私人bool IsImage(HttpPostedFileBase文件)
{
if(file.ContentType.Contains(image))
{
return true;
}
string [] formats = new string [] {.jpg,.png,.gif,.jpeg}; //添加更多,如果你喜欢...
// linq from HenrikStenbæk
return formats.Any(item => file.FileName.EndsWith(item,StringComparison.OrdinalIgnoreCase)) ;
}
我也写了一篇关于这个这里
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.)
I have tried with
using (var bitmapImage = new Bitmap (uploadFile.InputStream)) {..}
which throws an ArgumentException if bitmapImage can not be created.
Is there a better way for example by looking at uploadFile.FileName?
You can check the HttpPostedFileBase
object's properties for this
- ContentType
- FileName (check the file extensions, which you already know about :) )
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
这篇关于MVC3如何检查HttpPostedFileBase是否是一个图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!