2012-08-23 28 views
6

Tôi có chức năng tải tệp lên nơi người dùng có thể tải lên tệp. Tôi muốn hạn chế người dùng tải lên một số loại tệp nhất định. Các loại được phép là: .doc, .xlsx, .txt, .jpeg.Làm thế nào để hạn chế các loại tệp trong FileUpload trong MVC3?

Tôi có thể làm như thế nào?

Đây là mã tập tin tải lên thực tế của tôi:

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

Trả lời

19

Điều đầu tiên cần xác minh được liệu phần mở rộng tập tin chứa trong file1.FileName khớp với một trong các phần mở rộng cho phép. Sau đó, nếu bạn thực sự muốn đảm bảo rằng người dùng đã không đổi tên một số loại tệp khác thành tiện ích được cho phép, bạn sẽ cần phải xem xét nội dung của tệp để nhận ra đó có phải là một trong các loại được cho phép không.

Dưới đây là một ví dụ làm thế nào để kiểm tra xem phần mở rộng tập tin thuộc về một danh sách các phần mở rộng được xác định trước:

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

@Darrin Dimitrov .... làm thế nào tôi sẽ kiểm tra phần mở rộng bạn có thể cung cấp cho tôi bất kỳ mẫu – SoftwareNerd

+0

@Darrin Dimitrov .. .thanks xong và tôi đang hiển thị các tệp đã tải lên này trong bảng trước khi lưu Cơ sở dữ liệu ... nếu người dùng muốn xóa một trong các tệp đã tải lên, tôi có thể làm như thế nào ... – SoftwareNerd

6

Bạn có thể sử dụng ContentType tài sản của HttpPostedFileBase để kiểm tra cơ bản của các loại tập tin (loại mime) : See MSDN's page on the Content-Type property here

Dưới đây là một cách để làm điều đó:

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

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

vv ..

Tuy nhiên, để kiểm tra kỹ hơn, bạn sẽ phải kiểm tra nội dung tệp. Thật dễ dàng để thay đổi một phần mở rộng tập tin ..

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

Cách sử dụng trong mô hình

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

đây là câu trả lời thực tế –

+0

Đây là câu trả lời thực tế và súc tích. Cảm ơn bạn. –

Các vấn đề liên quan