6

I have my controller

[HttpPost]
public ActionResult ChangeAvatar(HttpPostedFileBase file)
{
    AvatarHelper.AvatarUpdate(file, User.Identity.Name);
    return RedirectToAction("Index", "Profile");
}

And I already check if file is in jpeg/png format:

private static bool IsImage(string contentType)
{   
  return AllowedFormats.Any(format => contentType.EndsWith(format,   
             StringComparison.OrdinalIgnoreCase));
}

public static List<string> AllowedFormats
{
    get { return new List<string>() {".jpg", ".png", ".jpeg"}; }
}

What I need - it ensure that uploaded file is real image file and not txt file with image extension.

I convert my uploaded file like this:

using (var image = System.Drawing.Image.FromStream(postedFile.InputStream))
{
          ///image stuff
}

I am thinking about try/catch block on creating image from input stream but I wonder if there is good way to do it? Thanks)

P.S.

I wonder if there is another (more efficient way that try/catch block) way to check whether file is real image?

4

2 回答 2

5

您可以使用该RawFormat属性:

private static ImageFormat[] ValidFormats = new[] { ImageFormat.Jpeg, ImageFormat.Png };
public bool IsValid(Stream image)
{
    try
    {
        using (var img = Image.FromStream(file.InputStream))
        {
            return ValidFormats.Contains(img.RawFormat);
        }
    }
    catch
    {
        return false;
    }
}

您也可以将此验证逻辑放入可重用的验证属性中,如我在this post.

于 2013-03-11T11:29:34.800 回答
2

我的解决方案作为扩展,实际检查 base64 字符串是否为图像:

public static bool IsImage(this string base64String)
    {
        byte[] imageBytes = Convert.FromBase64String(base64String);

        var stream = new MemoryStream(imageBytes, 0, imageBytes.Length);
        try
        {
            stream.Write(imageBytes, 0, imageBytes.Length);
            System.Drawing.Image image = System.Drawing.Image.FromStream(stream, true);
            return true;
        }
        catch (Exception)
        {
            return false;
        }
    }

用法:

if(!"base64string".IsImage())
     throw new Exception("Not an image");
于 2013-06-21T16:39:43.943 回答