locked
how can check the file size before upload, Please help RRS feed

  • Question

  • User-1355965324 posted

    I wan to upload the file having the maximum size 5mb ,  if not  it should  not be allowed to upload

    Here is my code, Please help me with suggested code

     public class EmpDocumentModel
        {
            [Key]
            public int EmpDocID { get; set; }
           
            public int EmployeeID { get; set; }
            public int DocCatID { get; set; }
            public int UserID { get; set; }
            public string NewFileName { get; set; }
            public DateTime CreatedDateAndTime { get; set; }
            public int ModifiedBy { get; set; }
            public DateTime? ModifiedDateAndTime { get; set; }
            public string Comment { get; set; }
            [NotMapped]
            public IFormFile FileNameURL { get; set; }
            [NotMapped]
            public string  EmpName {get;set;}
            [NotMapped]
            public string UploadedDate { get; set; }
    
            [NotMapped]
            public string CategoryName { get; set; }
    
            [DefaultValue(0)]
            public bool IsDeleted { get; set; }
    
            [DefaultValue(0)]
            public int DeletedBy { get; set; }
    
            public DateTime? DeletedDateAndTime { get; set; }
    
    
    
        }
    
     FileStream _file = new FileStream(filePath, FileMode.Create);
    // doc.FileNameURL.CopyTo(new FileStream(filePath, FileMode.Create)); // Here if mamimum size is greater 5mb , should not be allowed error should display
    doc.FileNameURL.CopyTo(_file);
    _file.Close();
    _file.Dispose();

    Tuesday, February 18, 2020 9:30 AM

Answers

  • User503812343 posted

    you can check _file.length property value which should be less than 5120 (5MB) or you can configure it in config file.

    system.web>
       <!-- maxRequestLength for asp.net, in KB --> 
       <httpRuntime maxRequestLength="5120" ></httpRuntime> 
    </system.web>
    
    <system.webServer>              
       <security> 
          <requestFiltering> 
             <!-- maxAllowedContentLength, for IIS, in bytes --> 
             <requestLimits maxAllowedContentLength="5242880" ></requestLimits>
          </requestFiltering> 
       </security>
    </system.webServer>

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Tuesday, February 18, 2020 10:18 AM

All replies

  • User503812343 posted

    you can check _file.length property value which should be less than 5120 (5MB) or you can configure it in config file.

    system.web>
       <!-- maxRequestLength for asp.net, in KB --> 
       <httpRuntime maxRequestLength="5120" ></httpRuntime> 
    </system.web>
    
    <system.webServer>              
       <security> 
          <requestFiltering> 
             <!-- maxAllowedContentLength, for IIS, in bytes --> 
             <requestLimits maxAllowedContentLength="5242880" ></requestLimits>
          </requestFiltering> 
       </security>
    </system.webServer>

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Tuesday, February 18, 2020 10:18 AM
  • User-1355965324 posted

    Is it possible to set up in my model class ? Please can you help me with the suggested code on the code given below. I would like to setup the maximum size on the model rather than config file

    Here is my code. The error message is not displayed  when I am trying to upload more than 5mb

    
    
    EmpDocumentModel class file
    public class EmpDocumentModel
        {
            [Key]
            public int EmpDocID { get; set; }
           
            public int EmployeeID { get; set; }
            public int DocCatID { get; set; }
            public int ModifiedBy { get; set; }
            public DateTime? ModifiedDateAndTime { get; set; }
            public string Comment { get; set; }
            [NotMapped]
            [MaxFileSize(5 * 1024 * 1024)]
            //[AllowedExtensions(new string[] { ".jpg", ".png" })]
            public IFormFile FileNameURL { get; set; }
            [NotMapped]
            public string  EmpName {get;set;}
            [NotMapped]
            public string UploadedDate { get; set; }
    
    
    
        }
    
    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.";
            }
        }
    

    In  View

    <div class="row">
            <form enctype="multipart/form-data"
                  asp-controller="EmpDoc"
                  asp-action="DocumentCreate"
                  data-ajax="true"
                  data-ajax-method="POST"
                  data-ajax-mode="replace"
                  data-ajax-update="#content"
                  class="form-horizontal"
                  role="form">
    
    <div class="col-md-6 ">
                                        <div class="form-group">
                                            <label asp-for="FileNameURL" class="control-label control-label-left col-sm-3 text-danger">File Name</label>
                                            <div class="col-sm-9">
                                                <div class="custom-file">
                                                    @*<input asp-for="FileNameURL" class="form-control custom-file-input">*@
                                                    <input type="file" id="FileNameURL" asp-for="FileNameURL" name="FileNameURL" class="form-control custom-file-input">
                                                    <span asp-validation-for="FileNameURL" class="input-group-btn text-danger">
                                                        @*<button class="btn btn-default" type="button" id="btnSelect">Browse...</button>*@
                                                    </span>
                                                </div>
                                            </div>
    
                                        </div>
    
                                    </div>          
    Controller
    ;HttpPost]
    public IActionResult DocumentCreate(EmpDocumentModel doc)
            {
                string uniqueFileName = null;
                int olddepot = doc.DepotNo;
                int olddept = doc.DepartmentID;
                int oldempid = doc.EmployeeID;
                try
                {
                    
    
                    string currentDate = DateTime.Now.ToString("ddMMyyyy");
    
                    
                    if (IsValidFilename(NewFileName))
                    {
                        if(!_unitOfWork.DocumentRepository.IsDuplicateFileName(NewFileName))
                        {
                            FileStream _file = new FileStream(filePath, FileMode.Create);
                           FileMode.Create));
                            doc.FileNameURL.CopyTo(_file);
                            _file.Close();
                            _file.Dispose();
    



    Tuesday, February 18, 2020 10:36 AM