asp.net-mvc 如何在 ASP.NET MVC 中验证上传的文件?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6388812/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 01:16:03  来源:igfitidea点击:

How to validate uploaded file in ASP.NET MVC?

asp.net-mvcsecurity

提问by Darin Dimitrov

I have a Create action that takes an entity object and a HttpPostedFileBase image. The image does not belong to the entity model.

我有一个 Create 操作,它接受一个实体对象和一个 HttpPostedFileBase 图像。图像不属于实体模型。

I can save the entity object in the database and the file in disk, but I am not sure how to validate these business rules:

我可以将实体对象保存在数据库中并将文件保存在磁盘中,但我不确定如何验证这些业务规则:

  • Image is required
  • Content type must be "image/png"
  • Must not exceed 1MB
  • 图片为必填项
  • 内容类型必须是“image/png”
  • 不得超过 1MB

回答by Darin Dimitrov

A custom validation attribute is one way to go:

自定义验证属性是一种方法:

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
        {
            using (var img = Image.FromStream(file.InputStream))
            {
                return img.RawFormat.Equals(ImageFormat.Png);
            }
        }
        catch { }
        return false;
    }
}

and then apply on your model:

然后应用于您的模型:

public class MyViewModel
{
    [ValidateFile(ErrorMessage = "Please select a PNG image smaller than 1MB")]
    public HttpPostedFileBase File { get; set; }
}

The controller might look like this:

控制器可能如下所示:

public class HomeController : Controller
{
    public ActionResult Index()
    {
        var model = new MyViewModel();
        return View(model);
    }

    [HttpPost]
    public ActionResult Index(MyViewModel model)
    {
        if (!ModelState.IsValid)
        {
            return View(model);
        }

        // The uploaded image corresponds to our business rules => process it

        var fileName = Path.GetFileName(model.File.FileName);
        var path = Path.Combine(Server.MapPath("~/App_Data"), fileName);
        model.File.SaveAs(path);

        return Content("Thanks for uploading", "text/plain");
    }
}

and the view:

和观点:

@model MyViewModel

@using (Html.BeginForm("Index", "Home", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
    @Html.LabelFor(x => x.File)
    <input type="file" name="@Html.NameFor(x => x.File)" id="@Html.IdFor(x => x.File)" />
    @Html.ValidationMessageFor(x => x.File)
    <input type="submit" value="upload" />
}

回答by Elizabeth Hamlet

Based on Darin Dimitrov's answer which I have found very helpful, I have an adapted version which allows checks for multiple file types, which is what I was initially looking for.

根据我发现非常有帮助的 Darin Dimitrov 的回答,我有一个改编版本,它允许检查多种文件类型,这正是我最初寻找的。

public override bool IsValid(object value)
    {
        bool isValid = false;
        var file = value as HttpPostedFileBase;

        if (file == null || file.ContentLength > 1 * 1024 * 1024)
        {
            return isValid;
        }

        if (IsFileTypeValid(file))
        {
            isValid = true;
        }

        return isValid;
    }

    private bool IsFileTypeValid(HttpPostedFileBase file)
    {
        bool isValid = false;

        try
        {
            using (var img = Image.FromStream(file.InputStream))
            {
                if (IsOneOfValidFormats(img.RawFormat))
                {
                    isValid = true;
                } 
            }
        }
        catch 
        {
            //Image is invalid
        }
        return isValid;
    }

    private bool IsOneOfValidFormats(ImageFormat rawFormat)
    {
        List<ImageFormat> formats = getValidFormats();

        foreach (ImageFormat format in formats)
        {
            if(rawFormat.Equals(format))
            {
                return true;
            }
        }
        return false;
    }

    private List<ImageFormat> getValidFormats()
    {
        List<ImageFormat> formats = new List<ImageFormat>();
        formats.Add(ImageFormat.Png);
        formats.Add(ImageFormat.Jpeg);
        formats.Add(ImageFormat.Gif);
        //add types here
        return formats;
    }
}

回答by Jeff D

Here is a way to do it using viewmodel, take a look at whole code here

这是一种使用 viewmodel 的方法,在这里查看整个代码

Asp.Net MVC file validation for size and typeCreate a viewmodel as shown below with FileSize and FileTypes

大小和类型的 Asp.Net MVC 文件验证创建一个视图模型,如下所示,使用 FileSize 和 FileTypes

public class ValidateFiles
{
    [FileSize(10240)]
    [FileTypes("doc,docx,xlsx")]
    public HttpPostedFileBase File { get; set; }
}

Create custom attributes

创建自定义属性

public class FileSizeAttribute : ValidationAttribute
{
    private readonly int _maxSize;

    public FileSizeAttribute(int maxSize)
    {
        _maxSize = maxSize;
    }
    //.....
    //.....
}



public class FileTypesAttribute : ValidationAttribute
{
    private readonly List<string> _types;

    public FileTypesAttribute(string types)
    {
        _types = types.Split(',').ToList();
    } 
    //....
    //...
}

回答by Evgeny Levin

And file length validation in asp.net core:

asp.net core 中的文件长度验证:

public async Task<IActionResult> MyAction()
{
    var form = await Request.ReadFormAsync();
    if (form.Files != null && form.Files.Count == 1)
    {
        var file = form.Files[0];
        if (file.Length > 1 * 1024 * 1024)
        {
            ModelState.AddModelError(String.Empty, "Maximum file size is 1 Mb.");
        }
    }
    // action code goes here
}

回答by BonyT

You may want to consider saving the image to database also:

您可能还需要考虑将图像保存到数据库:

  using (MemoryStream mstream = new MemoryStream())
                {
                    if (context.Request.Browser.Browser == "IE")
                        context.Request.Files[0].InputStream.CopyTo(mstream);
                    else
                        context.Request.InputStream.CopyTo(mstream);

                    if (ValidateIcon(mstream))
                    {
                        Icon icon = new Icon() { ImageData = mstream.ToArray(), MimeType = context.Request.ContentType };
                        this.iconRepository.SaveOrUpdate(icon);
                    }
                }

I use this with NHibernate - entity defined:

我将它与 NHibernate 一起使用 - 实体定义:

 public Icon(int id, byte[] imageData, string mimeType)
    {
        this.Id = id;
        this.ImageData = imageData;
        this.MimeType = mimeType;
    }

    public virtual byte[] ImageData { get; set; }

    public virtual string MimeType { get; set; }

Then you can return the image as a FileContentResult:

然后您可以将图像作为 FileContentResult 返回:

 public FileContentResult GetIcon(int? iconId)
    {
        try
        {
            if (!iconId.HasValue) return null;

            Icon icon = this.iconRepository.Get(iconId.Value);

            return File(icon.ImageData, icon.MimeType);
        }
        catch (Exception ex)
        {
            Log.ErrorFormat("ImageController: GetIcon Critical Error: {0}", ex);
            return null;
        }
    }

Note that this is using ajax submit. Easier to access the data stream otherwise.

请注意,这是使用 ajax 提交。否则更容易访问数据流。