我有一个这样的 Controller :
public ActionResult Upload (int id, HttpPostedFileBase uploadFile)
{
....
}
如何确保 uploadFile 是图像(jpg、png 等)
我试过
using (var bitmapImage = new Bitmap (uploadFile.InputStream)) {..}
如果无法创建 bitmapImage,则会抛出 ArgumentException。
是否有更好的方法,例如查看 uploadFile.FileName?
最佳答案
您可以为此检查 HttpPostedFileBase
对象的属性
- 内容类型
- 文件名(检查您已经知道的文件扩展名:))
还有一个小方法,我已经准备好了,你可以使用/扩展...
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));
}
我也写过一篇关于这个的文章here
关于c# - MVC3 如何检查 HttpPostedFileBase 是否是图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12120135/