[英]FileExtensions attribute of DataAnnotations not working in MVC
我試圖在MVC中使用HTML FileUpload控件上傳文件。 我想驗證該文件只接受特定的擴展名。 我已經嘗試使用DataAnnotations命名空間的FileExtensions屬性,但它不起作用。 見下面的代碼 -
public class FileUploadModel
{
[Required, FileExtensions(Extensions = (".xlsx,.xls"), ErrorMessage = "Please select an Excel file.")]
public HttpPostedFileBase File { get; set; }
}
在控制器中,我正在編寫如下代碼 -
[HttpPost]
public ActionResult Index(FileUploadModel fileUploadModel)
{
if (ModelState.IsValid)
fileUploadModel.File.SaveAs(Path.Combine(Server.MapPath("~/UploadedFiles"), Path.GetFileName(fileUploadModel.File.FileName)));
return View();
}
在View中,我寫了下面的代碼 -
@using (Html.BeginForm("Index", "FileParse", FormMethod.Post, new { enctype = "multipart/form-data"} ))
{
@Html.Label("Upload Student Excel:")
<input type="file" name="file" id="file"/>
<input type="submit" value="Import"/>
@Html.ValidationMessageFor(m => m.File)
}
當我運行應用程序並提供無效的文件擴展名時,它沒有顯示錯誤消息。 我知道編寫自定義驗證屬性的解決方案,但我不想使用自定義屬性。 請指出我哪里出錯了。
我有同樣的問題,我解決了創建一個新的ValidationAttribute。
像這樣:
[AttributeUsage(AttributeTargets.Field | AttributeTargets.Property, AllowMultiple = false, Inherited = true)]
public class FileExtensionsAttribute : ValidationAttribute
{
private List<string> AllowedExtensions { get; set; }
public FileExtensionsAttribute(string fileExtensions)
{
AllowedExtensions = fileExtensions.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries).ToList();
}
public override bool IsValid(object value)
{
HttpPostedFileBase file = value as HttpPostedFileBase;
if (file != null)
{
var fileName = file.FileName;
return AllowedExtensions.Any(y => fileName.EndsWith(y));
}
return true;
}
}
現在,只需使用:
[FileExtensions("jpg,jpeg,png,gif", ErrorMessage = "Your error message.")]
public HttpPostedFileBase Imagem { get; set; }
我幫了。 擁抱!
FileExtensions屬性不知道如何驗證HttpPostedFileBase。 請嘗試以下
[FileExtensions(Extensions = "xlsx|xls", ErrorMessage = "Please select an Excel file.")]
public string Attachment{ get; set; }
在你的控制器中:
[HttpPost]
public ActionResult Index(HttpPostedFileBase Attachment)
{
if (ModelState.IsValid)
{
if (Attachment.ContentLength > 0)
{
string filePath = Path.Combine(HttpContext.Server.MapPath("/Content/Upload"), Path.GetFileName(Attachment.FileName));
Attachment.SaveAs(filePath);
}
}
return RedirectToAction("Index_Ack"});
}
與marai回答一樣,FileExtension屬性僅適用於字符串屬性。
在我的代碼中,我使用如下屬性:
public class MyViewModel
{
[Required]
public HttpPostedFileWrapper PostedFile { get; set; }
[FileExtensions(Extensions = "zip,pdf")]
public string FileName
{
get
{
if (PostedFile != null)
return PostedFile.FileName;
else
return "";
}
}
}
然后,在服務器端,如果postedfile沒有您在屬性中指定的擴展名(在我的示例中為.zip和.pdf),則ModelState.IsValid將為false。
注意:如果您使用HTML.ValidationMessageFor
幫助程序在PostBack之后呈現錯誤消息(文件擴展名屬性未在客戶端驗證,僅在服務器端驗證),則需要為FileName
屬性指定另一個幫助程序以顯示擴展錯誤消息:
@Html.ValidationMessageFor(m => m.PostedFile)
@Html.ValidationMessageFor(m => m.FileName)
我在DataAnnotations的FileExtensions屬性中使用了上面的代碼, 而不是在MVC中工作 ,我只做了幾處更改:1)避免命名空間沖突和2)使用IFormFile而不是原始的HttpPostedFileBase。 好吧,也許對某人有用。
我的代碼:
[AttributeUsage(AttributeTargets.Field | AttributeTargets.Property, AllowMultiple = false, Inherited = true)]
public class FileVerifyExtensionsAttribute : ValidationAttribute
{
private List<string> AllowedExtensions { get; set; }
public FileVerifyExtensionsAttribute(string fileExtensions)
{
AllowedExtensions = fileExtensions.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries).ToList();
}
public override bool IsValid(object value)
{
IFormFile file = value as IFormFile;
if (file != null)
{
var fileName = file.FileName;
return AllowedExtensions.Any(y => fileName.EndsWith(y));
}
return true;
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.