[英]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 我希望它只允许PDF格式的文件,所以在我的模型中
[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. 并确保在页面上引用了jquery.validate.js
和jquery.validate.unobtrusive.js
以启用客户端验证。
Maybe you were missed jquery validate js files. 也许您错过了jquery验证js文件。
Make sure these code were in BundleConfig.cs: 确保这些代码在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));
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.