我在用ASP.NET Core 2.2,我使用模型绑定上传文件.

这是我的UserViewModel美元

public class UserViewModel
{
    [Required(ErrorMessage = "Please select a file.")]
    [DataType(DataType.Upload)]
    public IFormFile Photo { get; set; }
}

这是MyView

@model UserViewModel

<form method="post"
      asp-action="UploadPhoto"
      asp-controller="TestFileUpload"
      enctype="multipart/form-data">
    <div asp-validation-summary="ModelOnly" class="text-danger"></div>

    <input asp-for="Photo" />
    <span asp-validation-for="Photo" class="text-danger"></span>
    <input type="submit" value="Upload"/>
</form>

最后这是MyController

[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> UploadPhoto(UserViewModel userViewModel)
{
    if (ModelState.IsValid)
    {
        var formFile = userViewModel.Photo;
        if (formFile == null || formFile.Length == 0)
        {
            ModelState.AddModelError("", "Uploaded file is empty or null.");
            return View(viewName: "Index");
        }

        var uploadsRootFolder = Path.Combine(_environment.WebRootPath, "uploads");
        if (!Directory.Exists(uploadsRootFolder))
        {
            Directory.CreateDirectory(uploadsRootFolder);
        }

        var filePath = Path.Combine(uploadsRootFolder, formFile.FileName);
        using (var fileStream = new FileStream(filePath, FileMode.Create))
        {
            await formFile.CopyToAsync(fileStream).ConfigureAwait(false);
        }

        RedirectToAction("Index");
    }
    return View(viewName: "Index");
}

如何将上传的文件限制在5MB以下,并使用特定的扩展名,如.jpeg和.巴布亚新几内亚?我认为这两种验证都是在ViewModel中完成的.但我不知道该怎么做.

推荐答案

您可以自定义验证属性MaxFileSizeAttribute,如下所示

MaxFileSizeAttribute

public class MaxFileSizeAttribute : ValidationAttribute
{
    private readonly int _maxFileSize;
    public MaxFileSizeAttribute(int maxFileSize)
    {
        _maxFileSize = maxFileSize;
    }

    protected override ValidationResult IsValid(
    object value, ValidationContext validationContext)
    {
        var file = value as IFormFile;
        if (file != null)
        {
           if (file.Length > _maxFileSize)
            {
                return new ValidationResult(GetErrorMessage());
            }
        }

        return ValidationResult.Success;
    }

    public string GetErrorMessage()
    {
        return $"Maximum allowed file size is { _maxFileSize} bytes.";
    }
}

AllowedExtensionsAttribute

public class AllowedExtensionsAttribute : ValidationAttribute
{
    private readonly string[] _extensions;
    public AllowedExtensionsAttribute(string[] extensions)
    {
        _extensions = extensions;
    }
    
    protected override ValidationResult IsValid(
    object value, ValidationContext validationContext)
    {
        var file = value as IFormFile;
        if (file != null)
        {
            var extension = Path.GetExtension(file.FileName);
            if (!_extensions.Contains(extension.ToLower()))
            {
                return new ValidationResult(GetErrorMessage());
            }
        }
        
        return ValidationResult.Success;
    }

    public string GetErrorMessage()
    {
        return $"This photo extension is not allowed!";
    }
}

MaxFileSize属性和AllowedExtensions属性添加到Photo属性

public class UserViewModel
{
        [Required(ErrorMessage = "Please select a file.")]
        [DataType(DataType.Upload)]
        [MaxFileSize(5* 1024 * 1024)]
        [AllowedExtensions(new string[] { ".jpg", ".png" })]
        public IFormFile Photo { get; set; }
 }

Asp.net相关问答推荐

.Net Framework:w3wp.exe 中的异常

如何在 ASP.NET 中设置自动实现属性的默认值

带有模型的 mvc 上传文件 - 第二个参数发布的文件为空

系统日期时间?与 System.DateTime

如何将 viewbag 显示为 html?

ASP.NET web api 无法获取 application/x-www-form-urlencoded HTTP POST

静态字段与会话变量

asp.net dropdownlist - 在 db 值之前添加空行

ASP.NET - AppDomain.CurrentDomain.GetAssemblies() - AppDomain 重新启动后缺少程序集

ASP.NET MVC4 jquery/javascript 包的使用

Twitter bootstrap glyphicons 不会出现在发布模式 404 中

判断邮箱地址是否对 System.Net.Mail.MailAddress 有效

使下拉列表项不可 Select

在 asp.net 中将 JSON 转换为 .Net 对象时出错

MVC5 身份验证中的......与主域之间的信任关系失败

Owin.IAppBuilder不包含MapSignalR的定义

使 Web.config 转换在本地工作

如何从url中删除returnurl?

IE9 JavaScript 错误:SCRIPT5007:无法获取属性ui的值:对象为空或未定义

使用 FileUpload Control 获取文件的完整路径