0

I have a problem when I upload a file in ASP.NET MVC. My code is below:

public class RegisterForm
    {


        #region Ctor
        public RegisterForm()
        {

        }

        #endregion Ctor

        #region Properties

        [Key]
        [Required]
         public int ID { get; set; }


        [StringLength(50, ErrorMessage = " error")]
        [TypeConverter("NVarchar(121)")]
        public string FullName { get; set; }


        [RegularExpression(@"^[0-9]*$", ErrorMessage = "enter number")]
        [Remote("IsUserExists", "RegisterForms", ErrorMessage = "  ")]
        [StringLength(10, MinimumLength = 10, ErrorMessage = " length:10")]
        public String Mellicode { get; set; }

        [AllowFileSize(FileSize = 100 * 1024, ErrorMessage = "size:100kb")]
         //upload   
        public string FilePathName { get; set; }

}

AllowFileSize Notapply for FilePathName : code AllowFileSize

    [AttributeUsage(AttributeTargets.Field | AttributeTargets.Property, AllowMultiple = false, Inherited = true)]
    public class AllowFileSizeAttribute: ValidationAttribute
    {
        public int FileSize { get; set; } = 100 * 1024 ;


        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;
        }


    }

I used to uploadhelper:

public static class UploadHelper { public static MvcHtmlString Upload(this HtmlHelper helper, string name, object htmlAttributes = null) { //helper.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldName(ExpressionHelper.GetExpressionText(expression)) TagBuilder input = new TagBuilder("input"); input.Attributes.Add("type", "file"); input.Attributes.Add("id", helper.ViewData.TemplateInfo.GetFullHtmlFieldId(name)); input.Attributes.Add("name", helper.ViewData.TemplateInfo.GetFullHtmlFieldName(name));

    if (htmlAttributes != null)
    {
        var attributes = HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes);
        input.MergeAttributes(attributes);
    }

    return new MvcHtmlString(input.ToString());
}

}

controller:

public ActionResult Create([Bind(Include = "ID,FullName,Mellicode,FilePathName")] RegisterForm registerForm, HttpPostedFileBase UploadFile) { var myUniqueFileName = string.Format(@"{0}.txt", Guid.NewGuid());

        if (ModelState.IsValid)
        {

           string strFileExtension = System.IO.Path.GetExtension(UploadFile.FileName).ToUpper();


            string strContentType = UploadFile.ContentType.ToUpper();


            if ((UploadFile == null
            || (UploadFile.ContentLength == 0)
            || (UploadFile.ContentLength > 100 * 1024)))

            {
                                 return View("Error");
            }

            else
            {
                registerForm.FilePathName = myUniqueFileName + UploadFile.FileName;

                string strPath = Server.MapPath("~") + "App_Data\\";

                if (System.IO.Directory.Exists(strPath) == false)
                {
                    System.IO.Directory.CreateDirectory(strPath);
                }

                string strPathName =
                    string.Format("{0}\\{1}", strPath, registerForm.FilePathName);

                UploadFile.SaveAs(strPathName);
            }


            db.Registers.Add(registerForm);
            db.SaveChanges();
            return RedirectToAction("Back");
        }
        return View(registerForm);
    }

Create.cshtml:

@using (Html.BeginForm("Create", "RegisterForms", FormMethod.Post, new { enctype = "multipart/form-data", id = "UploadForm" })) { @Html.AntiForgeryToken()

        <form>
            @Html.ValidationSummary(true, "", new { @class = "text-danger" })
            <div class="A">

                <div class="form-group">
                    @Html.LabelFor(model => model.FullName, htmlAttributes: new { @class = "control-label col-md-10" })
                    <div class="col-md-10">
                        @Html.EditorFor(model => model.FullName, new { htmlAttributes = new { @class = "form-control"
                    }
                })
                        @Html.ValidationMessageFor(model => model.FullName, "", new { @class = "text-danger" })
                    </div>
                </div>

                <div class="form-group">
                    @Html.LabelFor(model => model.Mellicode, htmlAttributes: new { @class = "control-label col-md-10" })
                    <div class="col-md-10">
                        @Html.EditorFor(model => model.Mellicode, new { htmlAttributes = new { @class = "form-control" } })
                        @Html.ValidationMessageFor(model => model.Mellicode, "", new { @class = "text-danger" })

                    </div>
                </div>

                <div class="form-group">

                    @Html.LabelFor(model => model.FilePathName, htmlAttributes: new { @class = "control-label col-md-10" })
                    <div class="col-md-10">
                        @Html.Upload("UploadFile", new { htmlAttributes = new { @class = "form-control ", type = "file", id = "upload-id" } })

@Html.ValidationMessageFor(model => model.FilePathName, "", new { @class = "text-danger" })
                    </div>
                </div>

            </div>


            <div class="clearfix"></div>


                <input type="submit" style="   margin-right:25%" OnClientClick="return checkfile();" class="btn btn-info btn-lg   btn-responsive" id="search" value="send"   />





        </form>

}

sara
  • 31
  • 3
  • Possible duplicate of [Validating for large files upon Upload](https://stackoverflow.com/questions/10445861/validating-for-large-files-upon-upload) – vladimir May 19 '19 at 08:25
  • *AllowFileSize*-attribute assigned to **string**-property of viewmodel - it is wrong. – vladimir May 19 '19 at 08:27

0 Answers0