Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to restrict the file types in FileUpload in MVC3?

I have a fileupload function where users can upload files. I want to restrict the users from upload certain file types. The types allowed are: .doc,.xlsx,.txt,.jpeg.

How I can 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);
    }
like image 745
SoftwareNerd Avatar asked Aug 23 '12 06:08

SoftwareNerd


People also ask

What is HttpPostedFileBase?

The HttpPostedFileBase class is an abstract class that contains the same members as the HttpPostedFile class. The HttpPostedFileBase class lets you create derived classes that are like the HttpPostedFile class, but that you can customize and that work outside the ASP.NET pipeline.


2 Answers

The first thing to verify is whether the file extension contained in file1.FileName matches one of the allowed extensions. Then if you really want to ensure that the user hasn't renamed some other file type to an allowed extension you will need to look into the contents of the file to recognize whether it is one of the allowed types.

Here's an example how to check whether the 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
}
like image 176
Darin Dimitrov Avatar answered Oct 13 '22 01:10

Darin Dimitrov


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

Usage In Model

    [AllowedFileExtension(".jpg", ".png", ".gif", ".jpeg")]
    public HttpPostedFileBase KategoriResmi { get; set; }
like image 23
Paratoner Avatar answered Oct 12 '22 23:10

Paratoner