How to limit file types in FileUpload in MVC3?

I have a file upload function where users can upload files. I want to limit users to downloading certain types of files. Allowed types: .doc, .xlsx, .txt, .jpeg .

How can i do this?

This is my actual file upload code:

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); } 
+6
source share
3 answers

The first thing to check is whether the file extension contained in file1.FileName one of the allowed extensions. Then, if you really want to make sure that the user has not renamed any other type of file to the allowed extension, you will need to examine the contents of the file to see if it is one of the allowed types.

Here is an example of how to check if a file extension belongs to a list of predefined extensions:

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

You can use the ContentType property for HttpPostedFileBase for basic file type verification (mime type): See the MSDN page in -Type Content here

Here is one way to do this:

 private static bool IsValidContentType(string contentType) { string ct = contentType.ToLower(); return ((ct == "application/msword") || (ct == "application/pdf") || (ct == "application/vnd.openxmlformats-officedocument.wordprocessingml.document")); } 

etc..

However, for deeper control, you will need to check the contents of the file. Easy to change file extension.

+7
source
 [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; } } 

Use in the model

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

Source: https://habr.com/ru/post/923533/


All Articles