1

I need to upload a .XLSX file and I want to restrict other file format

My code

[Display(Name = "File Upload")]
[FileExtensions(Extensions = ".xlsx")]
public HttpPostedFileBase VendorFileType { get; set; }

REFERENCE LINK

Able to upload file without any restriction ( validation is not working ) Am working on MVC 5. Anyone share simple sample so restriction can be achieved ( Using only Data Annotations ( no jquery / javascript )

Community
  • 1
  • 1
Vinod
  • 596
  • 2
  • 10
  • 28
  • Solved by creating your own Custom Validation : http://stackoverflow.com/questions/15529540/asp-net-mvc-4-clientside-validation-not-working . Whom they are starting from basics. – Vinod Feb 09 '15 at 06:42

1 Answers1

2

file extension data annotations worked only on the string data.i solved this problem with help Validation Attribute that called is custom server side validation.
1.first create a Folder on the root your project called Validation.
2.on this folder create a class called FileExtensionValidation.this like code below:

public class FileExtensionsValidation : ValidationAttribute
{
    protected override ValidationResult IsValid(object value,ValidationContext validationContext)
    {
        if (value != null)
        {
            HttpPostedFileWrapper file = (HttpPostedFileWrapper)value;
            string extention = Path.GetExtension(file.FileName);

            if (extention != ".xlsx")
            {
                return new ValidationResult(".xlsx only");
            }
        }

    return ValidationResult.Success;

    }
}

3.on the top page add

Using ProjectName.ValidationFolderName;

4.attach validation above any file upload:

public class FileUploadViewModel:BaseViewModel
{        
    [Required]        
    [FileExtensionsValidation]
    public HttpPostedFileBase FileUpload { get; set; }     
}
Gareth
  • 5,140
  • 5
  • 42
  • 73
zokaee hamid
  • 522
  • 5
  • 16