简体   繁体   中英

File upload control to upload PDF only

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 ?

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.

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")

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


    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM