File upload control to upload PDF only

孤街浪徒 提交于 2019-12-11 03:23:56

问题


I got a file control like

 <div class="form-group">
        @Html.LabelFor(m => m.File, new { @class = "col-md-2 control-label" })
        <div class="col-md-10">
            @Html.TextBoxFor(m => m.File, new { type = "file" })

        </div>

I want it to allow only PDF format files, so in my model, its like

 [Display(Name = "Terms of Business")]
        [Required, FileExtensions(Extensions=".pdf", ErrorMessage="Incorrect file format")] 
        public HttpPostedFileBase File { get; set; }

However, the control still allows to upload documents of any format, why ?

What did I missed out ?


回答1:


Try regular expressions.

[RegularExpression(@"^(([a-zA-Z]:)|(\\{2}\w+)\$?)(\\(\w[\w].*))(.pdf|.PDF)$", ErrorMessage = "Incorrect file format")]

And make sure you have jquery.validate.js and jquery.validate.unobtrusive.js referenced on the page for enabling client side validation.




回答2:


Maybe you were missed jquery validate js files.

Make sure these code were in BundleConfig.cs:

bundles.Add(new ScriptBundle("~/bundles/jqueryval").Include(
                    "~/Scripts/jquery.unobtrusive*",
                    "~/Scripts/jquery.validate*"));

And put this code into view layer:

@Scripts.Render("~/bundles/jqueryval")



回答3:


You can try this code on button click event.

if (FileUpload1.HasFile)
    {
        if (FileUpload1.PostedFile.ContentType == "application/pdf")
        {
            Label1.Text = "File upload";
            string path = "images/" + FileUpload1.PostedFile.FileName;
            FileUpload1.SaveAs(Server.MapPath(path));
        }


    }


来源:https://stackoverflow.com/questions/22325828/file-upload-control-to-upload-pdf-only

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!