2012-08-23 43 views
6

我有一個文件上傳功能,用戶可以上傳文件。我想限制用戶上傳某些文件類型。允許的類型有:.DOC,.XLSX,txt文件,.JPEG如何在MVC3中限制FileUpload中的文件類型?

我該怎麼做?

這是我的實際文件上傳代碼:

 public ActionResult UploadFile(string AttachmentName, BugModel model) 
     {    
     BugModel bug = null; 
     if (Session["CaptureData"] == null) 
     { 
      bug = model; 
     } 
     else 
     { 
      bug = (BugModel)Session["CaptureData"]; 
     } 
     foreach (string inputTagName in Request.Files) 
     { 
      HttpPostedFileBase file1 = Request.Files[inputTagName]; 
      if (file1.ContentLength > 0) 
      { 
       string path = "/Content/UploadedFiles/" + Path.GetFileName(file1.FileName); 
       string savedFileName = Path.Combine(Server.MapPath("~" + path)); 
       file1.SaveAs(savedFileName); 
       BugAttachment attachment = new BugAttachment(); 
       attachment.FileName = "~" + path.ToString(); 
       attachment.AttachmentName = AttachmentName; 
       attachment.AttachmentUrl = attachment.FileName; 
       bug.ListFile.Add(attachment); 
       model = bug; 
       Session["CaptureData"] = model; 
      } 
     } 
     ModelState.Clear(); 
     return View("LoadBug", bug); 
    } 

回答

19

驗證的第一件事就是是否包含在file1.FileName文件擴展名匹配允許擴展之一。然後,如果您確實想確保用戶未將其他文件類型重命名爲允許的擴展名,則需要查看文件的內容以識別它是否是允許的類型之一。

下面是一個例子,如何檢查的文件擴展名是否屬於預定義的擴展名的列表:

var allowedExtensions = new[] { ".doc", ".xlsx", ".txt", ".jpeg" }; 
var extension = Path.GetExtension(file1.FileName); 
if (!allowedExtensions.Contains(extension)) 
{ 
    // Not allowed 
} 
+0

@Darrin季米特洛夫....我將如何檢查擴展,你可以給我提供任何樣品 – SoftwareNerd

+0

@Darrin季米特洛夫.. .thanks它做,我顯示此上傳表文件數據庫保存之前...如果用戶想要刪除上傳的文件我怎麼能做到這一點的一個... – SoftwareNerd

6

您可以使用HttpPostedFileBaseContentType財產的文件類型(MIME類型)的基本檢查:See MSDN's page on the Content-Type property here

下面是做到這一點的一種方法:

private static bool IsValidContentType(string contentType) 
{ 
    string ct = contentType.ToLower(); 

    return ((ct == "application/msword") || (ct == "application/pdf") || (ct == "application/vnd.openxmlformats-officedocument.wordprocessingml.document")); 
} 

等。

然而,進行更深層次的檢查,你將有權檢查文件內容。這很容易改變文件擴展..

7
[AttributeUsage(AttributeTargets.Property, AllowMultiple = false)] 
public class AllowedFileExtensionAttribute : ValidationAttribute 
{ 
    public string[] AllowedFileExtensions { get; private set; } 
    public AllowedFileExtensionAttribute(params string[] allowedFileExtensions) 
    { 
     AllowedFileExtensions = allowedFileExtensions; 
    } 
    protected override ValidationResult IsValid(object value, ValidationContext validationContext) 
    { 
     var file = value as HttpPostedFileBase; 
     if (file != null) 
     { 
      if (!AllowedFileExtensions.Any(item => file.FileName.EndsWith(item, StringComparison.OrdinalIgnoreCase))) 
      { 
       return new ValidationResult(string.Format("{1} için izin verilen dosya uzantıları : {0} : {2}", string.Join(", ", AllowedFileExtensions), validationContext.DisplayName, this.ErrorMessage)); 
      } 
     } 
     return null; 
    } 
} 

用法在型號

[AllowedFileExtension(".jpg", ".png", ".gif", ".jpeg")] 
    public HttpPostedFileBase KategoriResmi { get; set; } 
+2

這是實際的答案 –

+0

這是真實而簡潔的答案。謝謝。 –

相關問題