IFormFile - 最大文件大小的属性(以兆字节为单位)

问题描述 投票:0回答:2

对于 IFormFile 我们有属性:

[FileExtensions(Extensions ="jpg,png,gif,jpeg,bmp,svg")]

检查扩展名。

是否有任何属性可以检查文件大小(以兆字节为单位)或者我必须编写自己的属性?因为我想允许用户上传最大大小 = 2 MB 的文件。

asp.net-mvc asp.net-core
2个回答
9
投票

您没有指定框架。

ASP.NET:

您应该在 web.config 中指定以下内容:

<configuration>
  <system.web>
    <httpRuntime maxRequestLength="xxx" />
  </system.web>
</configuration>

ASP.NET 核心:

IIS

将此代码写入您的 web.config(此文件是在发布过程中生成的)

       <security>
        <requestFiltering>
          <!-- This will handle requests up to 10MB -->
          <requestLimits maxAllowedContentLength="10485760" />
        </requestFiltering>
      </security>

红隼

1、MVC解决方案:

[RequestSizeLimit(10485760)] 

按 Ctrl => 这是 10MB

2、全局指定IWebHostBuilder

  .UseKestrel(options =>
    {
        options.Limits.MaxRequestBodySize = 10485760; //10MB
    });

0
投票

就像您提到的,从今天开始我们需要创建一个自定义属性。这是一个快速的镜头。

public class MaxFileSizeAttribute : ValidationAttribute
{
    private readonly long _maxFileSize;

    public MaxFileSizeAttribute(long maxFileSize)
    {
        _maxFileSize = maxFileSize;
    }

    protected override ValidationResult IsValid(object value, ValidationContext validationContext)
    {
        if (value == null)
        {
            return ValidationResult.Success;
        }

        var file = value as IFormFile;

        if (file == null)
        {
            return new ValidationResult("Invalid file.");
        }

        if (file.Length > _maxFileSize)
        {
            return new ValidationResult($"File size cannot exceed {_maxFileSize} bytes.");
        }

        return ValidationResult.Success;
    }
}

并以这种方式使用它:

[MaxFileSize(10485760)] // For example, 10 MB in bytes
public IFormFile File { get; set; }
© www.soinside.com 2019 - 2024. All rights reserved.