0

When I click on the input and select a file, if the file size is small the viewModel returns non-null and saves the file in myfiles folder.

But if the file size is large, the controller is called before the file upload is not complete and the viewmodel returns null.

cshtml

<form class="form" method="post" enctype="multipart/form-data">

       <div class="form-group">
       <input asp-for="FirstName" class="form-control"/>
         <span asp-validation-for="FirstName" class="form-text text-danger"></span>
     </div>

     <div class="form-group">
      <input asp-for="LastName" class="form-control"/>
         <span asp-validation-for="LastName" class="form-text text-danger"></span>
       </div>

   <input type="file" asp-for="MyFile"/>
         </div>

    <button type="submit" class="btn btn-primary mr-2">Save</button>
         </form>

viewModel

   public class MyCarViewModel
    {
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public IFormFile MyFile{ set; get; }
    }

controller

       [HttpPost]
       public async Task<IActionResult> AddCar (MyCarViewModel viewModel)

            var fileName = "carfiles" + Path.GetExtension(viewModel.MyFile.FileName);
            var path = Path.Combine(Directory.GetCurrentDirectory(), "myfiles", fileName);

            using (var stream = new FileStream(path, FileMode.Create))
            {
                await viewModel.MyFile.CopyToAsync(stream);
            }

            var addViewModel = new MyCarViewModel()
            {
                FirstName = viewModel.FirstName,
                LastName = viewModel.LastName,
                UploadDocumentName = fileName,
            };

            dbContext.Car.Add(addViewModel);
            dbContext.SaveChanges();
  • What do you mean by "size is large"? 1Mb, 10Mb, 1GB? – Roman Marusyk May 29 '22 at 21:46
  • @RomanMarusyk 30 mb and above. – lovida5233 May 29 '22 at 21:55
  • 1
    By default, ASP.NET Core allows you to upload files up to 28 MB (approximately) in size. See [Increase upload file size in Asp.Net core](https://stackoverflow.com/questions/38698350/increase-upload-file-size-in-asp-net-core) – Roman Marusyk May 29 '22 at 23:08
  • Did you try to add `[DisableRequestSizeLimit, RequestFormLimits(MultipartBodyLengthLimit = int.MaxValue, ValueLengthLimit = int.MaxValue)]` on your `AddCar` action? – Rena May 30 '22 at 06:42

1 Answers1

0

first of all create a class like this :

  [AttributeUsage(AttributeTargets.Field | AttributeTargets.Property, AllowMultiple = false, Inherited = true)]  
public class AllowFileSizeAttribute : ValidationAttribute  
{  
    #region Public / Protected Properties  

    /// <summary>  
    /// Gets or sets file size property. Default is 1GB (the value is in Bytes).  
    /// </summary>  
    public int FileSize { get; set; } = 1 * 1024 * 1024 * 1024;  

    #endregion  

    #region Is valid method  

    /// <summary>  
    /// Is valid method.  
    /// </summary>  
    /// <param name="value">Value parameter</param>  
    /// <returns>Returns - true is specify extension matches.</returns>  
    public override bool IsValid(object value)  
    {  
        // Initialization  
        HttpPostedFileBase file = value as HttpPostedFileBase;  
        bool isValid = true;  

        // Settings.  
        int allowedFileSize = this.FileSize;  

        // Verification.  
        if (file != null)  
        {  
            // Initialization.  
            var fileSize = file.ContentLength;  

            // Settings.  
            isValid = fileSize <= allowedFileSize;  
        }  

        // Info  
        return isValid;  
    }  

    #endregion  
}  

In ASP.NET MVC5, creating customized data annotations/attributes is one of the cool features. In the above code, I have created a new class "AllowFileSizeAttribute" (by following the naming convention of custom attribute class) and inherited ValidationAttribute class. Then, I have created a public property "FileSize" and set its default value as 1 GB in bytes which means that my custom attribute will accept only uploaded files with a maximum file size less than or equal to 1 GB. So, in order to allow the required file size, this property will be updated at the time of my custom attribute utilization accordingly. Finally, I have overridden the "IsValid(....)" method which will receive my uploaded file as "HttpPostedFileBase" data type and from this, I will extract the file size of the upload file and then validated whether it is less than or equal to the default file size restriction or according to my provided file size.

Now create viewmodel like this :

public class ImgViewModel  
{  
    #region Properties  

    /// <summary>  
    /// Gets or sets Image file.  
    /// </summary>  
    [Required]  
    [Display(Name = "Upload File")]  
    [AllowFileSize(FileSize = 5 * 1024 * 1024, ErrorMessage = "Maximum allowed file size is 5 MB")]  
    public HttpPostedFileBase FileAttach { get; set; }  

    /// <summary>  
    /// Gets or sets message property.  
    /// </summary>  
    public string Message { get; set; }  

    /// <summary>  
    /// Gets or sets a value indicating whether file size is valid or not property.  
    /// </summary>  
    public bool IsValid { get; set; }  

    #endregion  
}  

below link also help you :

ASP.NET MVC 5 - Limit Upload File Size