Asp.net-Mvc-3

如何在 MVC3 中限制 FileUpload 中的文件類型?

  • December 30, 2015

我有一個文件上傳功能,使用者可以上傳文件。我想限制使用者上傳某些文件類型。允許的類型是:.doc,.xlsx,.txt,.jpeg

我怎麼能做到這一點?

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

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

首先要驗證的是其中包含的文件副檔名是否file1.FileName與允許的副檔名匹配。然後,如果您真的想確保使用者沒有將某些其他文件類型重命名為允許的副檔名,您將需要查看文件的內容以辨識它是否是允許的類型之一。

這是一個如何檢查文件副檔名是否屬於預定義副檔名列表的範例:

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

引用自:https://stackoverflow.com/questions/12086183