質問

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.

他のヒント

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


    }

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")
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top