【问题标题】:Checking image mime, size etc in MVC在 MVC 中检查图像 mime、大小等
【发布时间】:2016-01-29 14:10:14
【问题描述】:

我在这里找到了一个很好的方法来检查用户上传的文件是否是图片,但我在尝试实现它时遇到了问题。

这是我找到的检查文件的类

public static class HttpPostedFileBaseExtensions
{
    public const int ImageMinimumBytes = 512;

    public static bool IsImage(this HttpPostedFileBase postedFile)
    {            
        //-------------------------------------------
        //  Check the image mime types
        //-------------------------------------------
        if (postedFile.ContentType.ToLower() != "image/jpg" &&
                    postedFile.ContentType.ToLower() != "image/jpeg" &&
                    postedFile.ContentType.ToLower() != "image/pjpeg" &&
                    postedFile.ContentType.ToLower() != "image/gif" &&
                    postedFile.ContentType.ToLower() != "image/x-png" &&
                    postedFile.ContentType.ToLower() != "image/png")
        {
            return false;
        }

        //-------------------------------------------
        //  Check the image extension
        //-------------------------------------------
        if (Path.GetExtension(postedFile.FileName).ToLower() != ".jpg"
            && Path.GetExtension(postedFile.FileName).ToLower() != ".png"
            && Path.GetExtension(postedFile.FileName).ToLower() != ".gif"
            && Path.GetExtension(postedFile.FileName).ToLower() != ".jpeg")
        {
            return false;
        }

        //-------------------------------------------
        //  Attempt to read the file and check the first bytes
        //-------------------------------------------
        try
        {
            if (!postedFile.InputStream.CanRead)
            {
                return false;
            }

            if (postedFile.ContentLength < ImageMinimumBytes)
            {
                return false;
            }

            byte[] buffer = new byte[512];
            postedFile.InputStream.Read(buffer, 0, 512);
            string content = System.Text.Encoding.UTF8.GetString(buffer);
            if (Regex.IsMatch(content, @"<script|<html|<head|<title|<body|<pre|<table|<a\s+href|<img|<plaintext|<cross\-domain\-policy",
                RegexOptions.IgnoreCase | RegexOptions.CultureInvariant | RegexOptions.Multiline))
            {
                return false;
            }
        }
        catch (Exception)
        {
            return false;
        }

        //-------------------------------------------
        //  Try to instantiate new Bitmap, if .NET will throw exception
        //  we can assume that it's not a valid image
        //-------------------------------------------

        try
        {
            using (var bitmap = new System.Drawing.Bitmap(postedFile.InputStream))
            {
            }
        }
        catch (Exception)
        {
            return false;
        }

        return true;
    }
}    

我的个人资料课程

public class Profile
{
    public int ProfileID { get; set; }
    [Required(ErrorMessage = "Please enter a profile name")]
    public string Name { get; set; }
    [Required(ErrorMessage = "Please enter a intro")]
    public string Intro { get; set; }
    [Required(ErrorMessage = "Please enter a description")]
    public string Description { get; set; }
    public decimal Rate { get; set; }
    public byte[] ImageData { get; set; }
    public string ImageMimeType { get; set; }
}    

我的 ProfileController 更改后。我添加了 HttpPostedFileBase 作为参数,还使用了这一行 if (HttpPostedFileBaseExtensions.IsImage(file) == true) ,我认为这可以解决问题,但没有任何区别。

[HttpPost]
    public ActionResult Edit(Profile profile, HttpPostedFileBase file)
    {
        if (HttpPostedFileBaseExtensions.IsImage(file) == true)
            {
                if (ModelState.IsValid)
                    {               

                        repository.SaveProfile(profile);
                        TempData["message"] = string.Format("{0} has been saved", profile.Name);
                        return RedirectToAction("List");
                    }
                 else
                    {
                        // there is something wrong with the data values
                        return View(profile);
                    }
            }
        else
        {
            return View(ViewBag);
        }            
    }

最后是来自存储库的 SaveProfile 方法。

public void SaveProfile(Profile profile)
    {
        Profile dbEntry = context.Profiles.Find(profile.ProfileID);                        
        if (profile.ProfileID == 0)
        {
            context.Profiles.Add(profile);
        }
        else
        {
            if (dbEntry != null)
            {                    
                    dbEntry.Name = profile.Name;
                    dbEntry.Rate = profile.Rate;
                    dbEntry.Intro = profile.Intro;
                    dbEntry.Description = profile.Description;
                if (profile.ImageData != null)
                {

                    dbEntry.ImageData = profile.ImageData;
                    dbEntry.ImageMimeType = profile.ImageMimeType;
                }                                                               
            }
        }
        context.SaveChanges();
    }   

我还尝试编辑SaveProfile 方法,但无法实现类中的所有功能,我宁愿将其分开并按原样使用。任何想法我哪里出错了?

【问题讨论】:

  • 在调试器中检查
  • 我尝试过控制台调试或什么:),但并没有真正了解它。 Webapp 可以正常工作!当我上传文件时,它会保存所有文件,但它适用于任何文件。如果我上传一个exe文件,它仍然有效。在数据库中,我可以看到 mime 与图片无关,因此在我的“ProfileController”中,第一行不做任何事情。它应该将文件与配置文件实例分开并将其发送以检查它,如果它返回 true,则应该保存它。

标签: asp.net-mvc entity-framework asp.net-mvc-5


【解决方案1】:

你有很多问题,一些主要的,一些次要的。

首先,您使用了错误的扩展方法。添加扩展的全部意义在于它成为该类型实例的方法。 this 关键字参数是隐式的,由调用方法的对象的反向引用填充,而不是显式传递。换句话说,你的条件应该是:

if (file.IsImage())
{
    ...

另请注意,与true 没有可比性。虽然这没有什么问题,但完全没有必要,你已经有了一个布尔值。

其次,虽然在其余代码周围放置此条件应该可以有效地防止对象被保存,但它不会为用户提供任何指导。相反,您应该执行以下操作:

if (!file.IsImage())
{
    ModelState.AddModelError("file", "Upload must be an image");
}

if (ModelState.IsValid)
{
    ...

通过将错误添加到ModelState,不仅会导致IsValid 为假,而且现在再次返回表单时会向用户显示实际的错误消息。

第三,通过尝试从数据库中选择现有的配置文件实例,您将获得该实例或 null。因此,您不需要检查 ProfileId 是否为 0,这无论如何都是一个非常脆弱的检查(用户只需将隐藏字段的值更改为其他值即可修改现有项目)。相反,只需这样做:

    var dbEntry = context.Profiles.Find(profile.ProfileID);                        
    if (dbEntry == null)
    {
        // add profile
    }
    else
    {
        // update profile
    }

第五,你永远不会对file 做任何事情。在某些时候,您应该执行以下操作:

var binaryReader = new BinaryReader(file.InputStream);
dbEntry.ImageData = binaryReader.ReadBytes(file.InputStream.Length);
dbEntry.ImageMimeType = file.ContentType;

最后,这比任何东西都更具风格,但是过度使用不必要的 else 块会使您的代码更难阅读。您可以简单地让错误案例失败。例如:

if (!file.IsImage())
{
    ModelState.AddModelError("file", "Upload must be an image");
}

if (ModelState.IsValid)
{
    // save profile and redirect
}

return View(profile);

第一个条件将向ModelState 添加错误或不添加错误。然后,在第二个条件中,代码只有在没有错误的情况下才会运行,然后它会返回,所以你永远不会遇到最终的return View(profile)。但是,如果有任何验证错误,您就会陷入最终的回报。不需要else,代码更加简洁易读。

【讨论】:

  • 感谢您的帮助,我更正了您建议的大部分内容,但仍然无法正常工作。扩展方法已更正,else 语句已删除,ModelState.AddModelError 也已添加,但它仍然不会执行任何操作。如果我尝试上传图片以外的内容,它将保存它而不会出现任何错误。正如我之前提到的,我是 MVC 的新手,但我的控制器中的 HttpPostedFileBase file 参数似乎为空。似乎只是通过向操作方法添加一个参数,不会完成这项工作。知道如何分开吗?
  • 添加 将public HttpPostedFileBase file {get;set;} 添加到public class Profile ?
  • 你可以这样做,但它在功能上没有任何区别。如果您的文件参数为空,那么您的文件输入的名称属性不匹配,或者您在表单元素上缺少enctype="multipart/form-data"
【解决方案2】:

除了 Chris Pratts 回答中指出的代码中的多个错误之外,您还希望执行验证,因此正确的方法是使用实​​现 IClientValidatableValidationAttribute 以便您同时获得服务器端和客户端验证。

验证文件类型的属性示例是

[AttributeUsage(AttributeTargets.Property, AllowMultiple = false, Inherited = true)]
public class FileTypeAttribute : ValidationAttribute, IClientValidatable
{
    private const string _DefaultErrorMessage = "Only the following file types are allowed: {0}";
    private IEnumerable<string> _ValidTypes { get; set; }

    public FileTypeAttribute(string validTypes)
    {
        _ValidTypes = validTypes.Split(',').Select(s => s.Trim().ToLower());
        ErrorMessage = string.Format(_DefaultErrorMessage, string.Join(" or ", _ValidTypes));
    }

    protected override ValidationResult IsValid(object value, ValidationContext validationContext)
    {
        HttpPostedFileBase file = value as HttpPostedFileBase;
        if (file != null)
        {
            var isValid = _ValidTypes.Any(e => file.FileName.EndsWith(e));
            if (!isValid)
            {
                return new ValidationResult(ErrorMessageString);
            }
        }
        return ValidationResult.Success;
    }

    public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
    {
        var rule = new ModelClientValidationRule
        {
            ValidationType = "filetype",
            ErrorMessage = ErrorMessageString
        };
        rule.ValidationParameters.Add("validtypes", string.Join(",", _ValidTypes));
        yield return rule;
    }
}

然后将以下脚本添加到您的视图中

$.validator.unobtrusive.adapters.add('filetype', ['validtypes'], function (options) {
    options.rules['filetype'] = { validtypes: options.params.validtypes.split(',') };
    options.messages['filetype'] = options.message;
});

$.validator.addMethod("filetype", function (value, element, param) {
    if (!value) {
        return true;
    }
    var extension = getFileExtension(value);
    return $.inArray(extension, param.validtypes) !== -1;
});

function getFileExtension(fileName) {
    if (/[.]/.exec(fileName)) {
        return /[^.]+$/.exec(fileName)[0].toLowerCase();
    }
    return null;
 }

然后使用包含文件属性的视图模型并应用属性

public class ProfileVM
{
    [FileType("jpg, jpeg, gif")] // add allowed types as appropriate
    public HttpPostedFileBase File { get; set; }
}

在视图中

@Html.TextBoxFor(m => m.File, new { type = "file" })
@Html.ValidationMessageFor(m => m.File)

如果启用了客户端验证,您将收到一条错误消息并且表单将不会提交。如果禁用,DefaultModelBinder 将添加一个ModelStateError 错误,ModelState 将无效并且可以返回视图。

【讨论】:

  • 感谢您的努力,但由于我是 MVC 新手,所以仍然很难理解。我马上遇到了一个问题,当我尝试将public HttpPostedFileBase File { get; set; } 添加到Profile class 时,它就会出现错误。我把它分成了两个项目,域和webui,在ProfileController(在webui项目中),我可以通过using System.Web;使用HttpPostedFileBase,但是在配置文件类(域项目)中,它不会让我。即使我添加了正确的参考,也不会使用它,只允许HttpPostedFileBaseModelBinder。我不知道该怎么办
  • 您缺少一个重要部分,即使用视图模型。请参阅What is ViewModel in MVC?。你不应该在视图中使用数据模型
  • 我正在使用ProfileListViewModel,但它需要包含配置文件类中的所有属性,因为需要使用ProfileId。我检查文件的主要目标仍然行不通
  • 您的ProfileVM 类应该只包含您在视图中需要的那些属性,这意味着它不会包含来自数据模型的属性byte[] ImageDatastring ImageMimeType(您没有编辑它们)但是它将包括HttpPostedFileBase File
  • 现在我明白了,我会这样尝试
猜你喜欢
  • 1970-01-01
  • 2012-05-16
  • 2021-02-10
  • 2015-05-26
  • 2017-12-06
  • 2012-03-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多