Как проверить загруженный файл в ASP.Net Core - PullRequest
0 голосов
/ 14 июня 2019

Я использую 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");
}

Как ограничить количество загружаемых файлов до 5 МБ с определенными расширениями, такими как .jpeg и .png?Я думаю, что обе эти проверки выполняются во ViewModel.Но я не знаю, как это сделать.

Ответы [ 3 ]

1 голос
/ 14 июня 2019

Вы можете настроить атрибут 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;
        //var extension = Path.GetExtension(file.FileName);
        //var allowedExtensions = new[] { ".jpg", ".png" };`enter code here`
        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;
        var extension = Path.GetExtension(file.FileName);
        if (!(file == null))
        {
            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; }
 }
1 голос
/ 14 июня 2019

Вы можете IValidatableObject подтвердить свою модель.

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

        public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
        {
            var photo = ((UserViewModel)validationContext.ObjectInstance).Photo;
            var extension = Path.GetExtension(photo.FileName);
            var size = photo.Length;

            if (!extension.ToLower().Equals(".jpg"))
                yield return new ValidationResult("File extension is not valid.");

           if(size > (5 * 1024 * 1024))
                yield return new ValidationResult("File size is bigger than 5MB.");
        }
    }
0 голосов
/ 14 июня 2019

Вы можете сделать как ниже код

    var formFile = userViewModel.Photo;
    var extension = Path.GetExtension(formFile.FileName);
    var allowedExtensions = new[] { ".jpeg", ".png" };

    if (formFile == null || formFile.Length == 0)
    {
        ModelState.AddModelError("", "Uploaded file is empty or null.");
        return View(viewName: "Index");
    }


    if (formFile != null && formFile.ContentLength > 0 && 
     allowedExtensions.Contains(extension.ToLower()) 
     && formFile.ContentLength <= (5 * 1024 * 1024))
    {
        //do some logic here because the data is smaller than 5mb   

    }
    else 
    { 
        // error
        return View("Error");
    }
...