上传前检查文件大小

时间:2019-05-19 08:16:05

标签: c# asp.net-mvc-5 attributes

在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不适用于FilePathName: 代码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;
        }


    }

我曾经上载过helper:

公共静态类UploadHelper {     公共静态MvcHtmlString上传(此HtmlHelper帮助器,字符串名称,对象htmlAttributes = null)     {         //helper.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldName(ExpressionHelper.GetExpressionText(expression))         TagBuilder输入=新的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创建([绑定(包括=“ 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(“创建”,“ RegisterForms”,FormMethod.Post,新的{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>

}

0 个答案:

没有答案