afzal February 2016

Max file size validation attribute is not working in mvc 4

My problem is that if I upload the file more than 4 mb throwing exception "Maximum request length exceeded."

My requirements is that: Should show the validation error message.I am not sure whether i'm wrong. Please help me some one

Thanks

public class FileSizeAttribute : ValidationAttribute
    {
    private long _maxSize;

    /// <summary>
    /// Default constructor. defines maximum size of the file.
    /// </summary>
    public FileSizeAttribute()
    {
         _maxSize = Convert.ToInt32(ConfigurationManager.AppSettings["FileSize"]);
    }

    /// <summary>
    /// Override IsValid method to validate the decorated property
    /// </summary>
    /// <param name="value"></param>
    /// <returns></returns>
    public override bool IsValid(object value)
    {
        var file = value as HttpPostedFileBase;

        if (file == null) return true;

        return file.ContentLength <= _maxSize;
    }

    /// <summary>
    /// Override format message method to return failure message.
    /// </summary>
    /// <param name="name"></param>
    /// <returns></returns>
    public override string FormatErrorMessage(string name)
    {
        return string.Format("The file size should not exceed {0} MB", Math.Ceiling((_maxSize / 1024f) / 1024f));
    }
}

Property Model:

     [FileSize]
    [FileTypes]
    public HttpPostedFileBase File

In Web Config file

<httpRuntime maxRequestLength="10240" targetFramework="4.5" />

Answers


Shah NIral February 2016

Use MaxFileSize In Model Property Directly

[Required]
[MaxFileSize(10 * 1024 , ErrorMessage = "Maximum allowed file size is {0} bytes")]

OR

See This

Post Status

Asked in February 2016
Viewed 1,570 times
Voted 10
Answered 1 times

Search




Leave an answer