文件上传控件仅用于上传PDF

时间:2014-03-11 12:30:56

标签: c# asp.net-mvc file-upload format html-helper

我有一个像

这样的文件控件
 <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>

我希望它只允许PDF格式文件,所以在我的模型中,它就像

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

但是,控件仍然允许上传任何格式的文档,为什么?

我错过了什么?

3 个答案:

答案 0 :(得分:4)

尝试正则表达式。

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

并确保您在页面上引用jquery.validate.jsjquery.validate.unobtrusive.js以启用客户端验证。

答案 1 :(得分:1)

也许你错过了 jquery validate js 文件。

确保这些代码在BundleConfig.cs中:

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

并将此代码放入视图层:

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

答案 2 :(得分:1)

您可以在按钮点击事件上尝试此代码。

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


    }