File upload control to upload PDF only

12,044

Solution 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.

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

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


    }
Share:
12,044
Nishant Rambhojun
Author by

Nishant Rambhojun

Updated on June 05, 2022

Comments

  • Nishant Rambhojun
    Nishant Rambhojun almost 2 years

    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 ?