Проверьте размер файла перед загрузкой - PullRequest
0 голосов
/ 19 мая 2019

У меня проблема при загрузке файла в ASP.NET MVC.Мой код ниже:

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 для 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;
        }


    }

Я использовал для загрузки:

публичный статический класс UploadHelper {публичный статический MvcHtmlString Upload(этот вспомогательный HtmlHelper, имя строки, объект 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());
}

}

контроллер:

публичный 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>

}

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...