【问题标题】:File upload control to upload PDF only文件上传控件仅上传 PDF
【发布时间】:2014-03-11 12:30:55
【问题描述】:

我有一个类似的文件控件

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

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

我错过了什么?

【问题讨论】:

  • 您的相同代码对我来说效果很好。正如 Zafar 在他的回答中提到的,你一定错过了那些 js 文件。另外,您还应该在视图中添加@Html.ValidationSummary()

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


【解决方案1】:

试试正则表达式。

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

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

【讨论】:

    【解决方案2】:

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

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

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

    并将这段代码放入视图层:

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

    【讨论】:

      【解决方案3】:

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

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

      【讨论】:

        猜你喜欢
        • 2011-06-29
        • 1970-01-01
        • 2011-12-08
        • 1970-01-01
        • 2014-04-19
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多