MVC3 How to check if HttpPostedFileBase is an image

前端 未结 3 2017
野的像风
野的像风 2021-01-31 18:13

I have a controller like this:

public ActionResult Upload (int id, HttpPostedFileBase uploadFile)
{
....
}

How can I make sure that uploadFile

3条回答
  •  甜味超标
    2021-01-31 18:29

    You can check the HttpPostedFileBase object's properties for this

    • ContentType
    • FileName (check the file extensions, which you already know about :) )

    enter image description here

    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

提交回复
热议问题