MVC3如何检查HttpPostedFileBase是否为图像

Hen*_*bæk 22 c# file-upload httppostedfilebase asp.net-mvc-3

我有一个像这样的控制器:

public ActionResult Upload (int id, HttpPostedFileBase uploadFile)
{
....
}
Run Code Online (Sandbox Code Playgroud)

我怎样才能确保uploadFile是一个图像(jpg,png等)

我试过了

using (var bitmapImage = new Bitmap (uploadFile.InputStream)) {..}
Run Code Online (Sandbox Code Playgroud)

如果无法创建bitmapImage,则会抛出ArgumentException.

有没有更好的方法,例如通过查看up​​loadFile.FileName?

Yas*_*ser 61

您可以检查HttpPostedFileBase对象的属性

  • 内容类型
  • FileName(检查文件扩展名,你已经知道:))

在此输入图像描述

这里还有一个小方法,我准备了你可以使用/扩展...

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));
}
Run Code Online (Sandbox Code Playgroud)

我也在这里写了一篇文章


Dar*_*rov 19

您可以检查文件名和扩展名以及MIME类型,但这可能不可靠,因为用户可以在上传之前简单地重命名该文件.这是通过查看文件内容实现这一目标的可靠方法:https://stackoverflow.com/a/6388927/29407

您当然可以将此扩展到除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;
    }
}
Run Code Online (Sandbox Code Playgroud)